要将ViewPager与TabLayout配合使用,可以通过以下步骤:
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
app:tabMode="scrollable"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
TabLayout tabLayout = findViewById(R.id.tabLayout);
ViewPager viewPager = findViewById(R.id.viewPager);
MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private int numOfTabs;
public MyPagerAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Tab1Fragment();
case 1:
return new Tab2Fragment();
case 2:
return new Tab3Fragment();
default:
return null;
}
}
@Override
public int getCount() {
return numOfTabs;
}
}
public class Tab1Fragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_layout, container, false);
return view;
}
}
// 同样创建Tab2Fragment和Tab3Fragment类
这样就可以实现ViewPager与TabLayout的配合使用,并通过PagerAdapter管理各个页面的显示。