1.布局文件:
<?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=".MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tab"
app:tabGravity="fill"
app:tabTextAppearance="@style/TabLayoutTextStyle"
android:layout_width="match_parent"
android:layout_height="50dp"></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
</LinearLayout>
2.actvivty主页
public class MainActivity extends AppCompatActivity {
private ViewPager vp;
private ArrayList<Fragment> fraglist;
private ArrayList<String> tablist;
private TabLayout tab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tab = (TabLayout) findViewById(R.id.tab);
vp = (ViewPager) findViewById(R.id.vp);
fraglist = new ArrayList<>();
fraglist.add(new Frag01());
fraglist.add(new Frag02());
fraglist.add(new Frag03());
fraglist.add(new Frag04());
tablist = new ArrayList<>();
tablist.add("页面1");
tablist.add("页面2");
tablist.add("页面3");
tablist.add("页面4");
MyPageAdapter myPageAdapter = new MyPageAdapter(getSupportFragmentManager(), fraglist, tablist);
vp.setAdapter(myPageAdapter);
tab.setupWithViewPager(vp);
}
}
3.FragmentPagerAdapter 适配器
public class MyPageAdapter extends FragmentPagerAdapter {
private Context context;
private ArrayList<Fragment> list;
private ArrayList<String> lists;
public MyPageAdapter(FragmentManager fm, ArrayList<Fragment> list, ArrayList<String> lists) {
super(fm);
this.list = list;
this.lists = lists;
}
@Override
public Fragment getItem(int i) {
return list.get(i);
}
@Override
public int getCount() {
return list.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return lists.get(position);
}