橫向滑動選單:horizontalscrollview+viewpager+Fragment
阿新 • • 發佈:2019-02-11
MainActivity extends AppCompatActivity implements View.OnClickListener {
private HorizontalScrollView scrollView;
private LinearLayout linearLayout;
private ViewPager viewPager;
private String[] titles;
private ArrayList<TextView> list;
private LinearLayout.LayoutParams params ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取控制元件
scrollView = (HorizontalScrollView) findViewById(R.id.Scrollview);
linearLayout = (LinearLayout) findViewById(R.id.Linearlayout );
viewPager = (ViewPager) findViewById(R.id.Viewpager);
//建立資料來源
titles = new String[]{"頭條", "社會", "國內", "國際", "娛樂", "體育", "軍事", "科技", "財經", "時尚"};
//建立集合
list = new ArrayList<>();
//設定資料
initdata();
//建立介面卡
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return fragment.getinfo(list.get(position).getText().toString());
}
@Override
public int getCount() {
return titles.length;
}
});
//監聽
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
for (int i = 0; i < list.size(); i++) {
if (position == i) {
list.get(i).setTextColor(Color.RED);
} else {
list.get(i).setTextColor(Color.BLACK);
}
}
TextView textView = list.get(position);
int width = textView.getWidth();//獲取寬度
//計算該滑到哪裡
scrollView.scrollTo((width + 20) * position, 0);//viewpager滑動時與滾動控制元件想配合一起滑動
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void onClick(View view) {
int id = view.getId();
viewPager.setCurrentItem(id - 10000);
}
private void initdata() {
//新增資料,設定寬高,設定字型顏色
for (int i = 0; i < titles.length; i++) {
//自己定義一個textview
TextView view = new TextView(this);
//把資料放入textview裡
view.setText(titles[i]);
//設定資料最大小
view.setTextSize(20);
//通過判斷剛進入為黑色,否則為紅色
if (i == 0) {
view.setTextColor(Color.RED);
} else {
view.setTextColor(Color.BLACK);
}
//給textview設定點選事件
view.setOnClickListener(this);
view.setId(i + 10000);
//設定textview控制元件的寬高
params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//通過寬高設定neibianju
params.setMargins(20, 10, 20, 10);
//將textview控制元件新增到滾動控制元件裡面的LinearLayout佈局
linearLayout.addView(view, params);
//把資料新增到集合
list.add(view);
}
}
}
//class類