public class MainActivity extends AppCompatActivity implements View.OnClickListener{ HorizontalScrollView hsv;//横向滚动布局 LinearLayout ll; //线性结构,在横滚动布局里面 ViewPager vp; ArrayList<TextView> arr; String[] titles; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); hsv = (HorizontalScrollView) findViewById(R.id.horizontalsv); ll = (LinearLayout) findViewById(R.id.liinerlyout); vp = (ViewPager) findViewById(R.id.viewpager); titles = new String[] { "头条", "娱乐", "科技", "信息", "八卦", "北京", "上海", "天津", "重庆", "大大燕网", "富地", "dsaf", "greg", "ffdsew", "fdbdn"}; arr = new ArrayList<TextView>(); for(int i=0;i<titles.length;i++){ TextView te = new TextView(MainActivity.this); te.setText(titles[i]); te.setId(i+1000); te.setOnClickListener(this); if(i==0){ te.setTextColor(Color.RED); }else{ te.setTextColor(Color.BLACK); } LinearLayout.LayoutParams lin = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); lin.setMargins(20,10,20,10); ll.addView(te,lin); arr.add(te); } MyAdpt myadpt = new MyAdpt(getSupportFragmentManager()); vp.setAdapter(myadpt); //ViewPager的滑动事件 vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { for(int t=0;t<arr.size();t++){ if(t==i){ arr.get(t).setTextColor(Color.RED); }else{ arr.get(t).setTextColor(Color.BLACK); } } TextView textView = arr.get(i); int i2 = textView.getWidth()/arr.size()*i; hsv.smoothScrollBy(i2,0); } @Override public void onPageSelected(int i) { } @Override public void onPageScrollStateChanged(int i) { } }); } class MyAdpt extends FragmentPagerAdapter{ public MyAdpt(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) {
//返回的是建的一个Fragment里的方法,用Bundle传值的 return XinFragment.getIntance(arr.get(i).getText().toString()); } @Override public int getCount() { return arr.size(); } } @Override public void onClick(View view) { int in = view.getId(); vp.setCurrentItem(in-1000); } }