xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_zhuye"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.bwie.yuekaomoni.ZhuyeActivity">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tablayout">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewpager" />
</LinearLayout>
MainActivtiy中
public class ZhuyeActivity extends AppCompatActivity{
private TabLayout tabLayout;
private ViewPager viewPager;
private FragmentAdapter fragmentAdapter;
private ArrayList<Fragment> fragments;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zhuye);
tabLayout= (TabLayout) findViewById(R.id.tablayout);
viewPager= (ViewPager) findViewById(R.id.viewpager);
fragments=new ArrayList<Fragment>();
FragmentOne fragment1 = new FragmentOne();
FragmentTwo fragment2 = new FragmentTwo();
FragmentThree fragment3 = new FragmentThree();
FragmentFour fragment4 = new FragmentFour();
fragments.add(fragment1);
fragments.add(fragment2);
fragments.add(fragment3);
fragments.add(fragment4);
fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(),fragments);
viewPager.setAdapter(fragmentAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
建四个fragment和xml