布局
<hqyhkj.com.yhshop.view.UILinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#2D77ED"
app:tabIndicatorHeight="1dp"
app:tabTextColor="#333333"
app:tabSelectedTextColor="#2D77ED"
uipx:ui_bottomPadding="8"
uipx:ui_leftMargin="24"
uipx:ui_rightMargin="24"
/>
<hqyhkj.com.yhshop.view.MyViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</hqyhkj.com.yhshop.view.UILinearLayout>
代码
List<BaseFragment> fragmentList;
TabLayout tabLayout;
ViewPager viewPager;
MyFragmentPagerAdapter myFragmentPagerAdapter;
private void sixTab() {
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
//准备4个fragment
fragmentList.add(new ShopInfoFragment());
fragmentList.add(new StoreDongTaiFragment());
fragmentList.add(new StorePinLunFragment());
fragmentList.add(new StoreInfoFragment());
tabLayout.setupWithViewPager(viewPager);
myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
viewPager.setAdapter(myFragmentPagerAdapter);
//将TabLayout与ViewPager绑定在一起
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private String[] mTitles = new String[]{"商品信息", "动态", "评论","商家信息"};
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return mTitles.length;
}
//ViewPager与TabLayout绑定后,这里获取到PageTitle就是Tab的Text
@Override
public CharSequence getPageTitle(int position) {
return mTitles[position];
}
}