布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.model_fragment.view.activity.Main2Activity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_item_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal" android:text="菜单一" /> <TextView android:id="@+id/tv_item_tow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal" android:text="菜单二" /> <TextView android:id="@+id/tv_item_three" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal" android:text="菜单三" /> </LinearLayout> <android.support.v4.view.ViewPager android:id="@+id/viewpager_main2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1"></android.support.v4.view.ViewPager> </LinearLayout>
java代码
private TextView textView1; private TextView textView2; private TextView textView3; private ViewPager viewPager; private List<Fragment> list = new ArrayList<>(); private MyFragmentAdapter myFragmentAdapter; @Override protected void initData() { textView1.setOnClickListener(this); textView2.setOnClickListener(this); textView3.setOnClickListener(this); viewPager.setOnPageChangeListener(this); AFragment aFragment = new AFragment(); BFragment bFragment = new BFragment(); CFragment cFragment = new CFragment(); list.add(aFragment); list.add(bFragment); list.add(cFragment); myFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(),list); viewPager.setAdapter(myFragmentAdapter); viewPager.setCurrentItem(0); } @Override protected void initView() { textView1 = (TextView) findViewById(R.id.tv_item_one); textView2 = (TextView) findViewById(R.id.tv_item_tow); textView3 = (TextView) findViewById(R.id.tv_item_three); viewPager = (ViewPager) findViewById(R.id.viewpager_main2); } @Override protected int getLayoutId() { return R.layout.activity_main2; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.tv_item_one: viewPager.setCurrentItem(0); break; case R.id.tv_item_tow: viewPager.setCurrentItem(1); break; case R.id.tv_item_three: viewPager.setCurrentItem(2); break; } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position){ case 0: break; case 1: break; case 2: break; } } @Override public void onPageScrollStateChanged(int state) { }