XML:
<android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="50dp">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v4.view.ViewPager>
Activity:
private List<Fragment> list;
private ViewPager viewPager;
private TabLayout tab;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragmenttwo,container,false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//获取资源ID
viewPager = view.findViewById(R.id.pager);
tab = view.findViewById(R.id.tab);
list=new ArrayList<>();
list.add(new Fragone());
list.add(new Fragtwo());
viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
@Override
public Fragment getItem(int i) {
return list.get(i);
}
@Override
public int getCount() {
return list.size();
}
});
//tab.addTab(tab.newTab());
//tab.addTab(tab.newTab());
//绑定viewpager
tab.setupWithViewPager(viewPager);
//标题的名字
tab.getTabAt(0).setText("正在热播");
tab.getTabAt(1).setText("即将上映");
}