第一步:输入design就能出来
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
app:tabGravity="fill"
app:tabIndicatorColor="@color/too"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/too"
app:tabTextColor="#000"
/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
主页面的代码
public class FragOnew extends Fragment {
private TabLayout tab;
private ViewPager pager;
private ArrayList<Fragment> arr;
private ArrayList<String> title;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_one, container, false);
//第二步:控件TabLayout
tab = view.findViewById(R.id.tab);
pager = view.findViewById(R.id.pager);
//第三步:创建Fragment集合
arr = new ArrayList<>();
arr.add(new TabOne());
arr.add(new TabTwo());
//第四步:创建文本集合
title = new ArrayList<>();
title.add("one");
title.add("two");
//第五步:设置适配器
pager.setAdapter(new MyPagerAdapter(getActivity().getSupportFragmentManager(),arr, title));
//第七步:绑定
tab.setupWithViewPager(pager);//此方法就是让tablayout和ViewPager联动
return view;
}
}
适配器:
public class MyPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> arr;
private ArrayList<String> tit;
public MyPagerAdapter(FragmentManager fm, ArrayList<Fragment> arr,ArrayList<String> tit) {
super(fm);
this.arr=arr;
this.tit=tit;
}
@Override
public Fragment getItem(int i) {
return arr.get(i);
}
@Override
public int getCount() {
return arr.size();
}
//此方法用来显示tab上面的名字
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return tit.get(position);
}
}