public class MainActivity extends AppCompatActivity {
private TabLayout tabId;
private ViewPager vpId;
private List list=new ArrayList();
private List titles=new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabId= findViewById(R.id.tab);
vpId=findViewById(R.id.vp);
list.add(new one());
list.add(new two());
list.add(new four());
titles.add("首页");
titles.add("第二页");
titles.add("第三页");
//适配器
MyFragmentAdapter myFragmentAdapter=new MyFragmentAdapter(getSupportFragmentManager(),list,titles);
//关联
vpId.setAdapter(myFragmentAdapter);
//把viewPager和tabLayout绑定在一起
tabId.setupWithViewPager(vpId);
}
class MyFragmentAdapter extends FragmentStatePagerAdapter {
private List list;
private List titles;
public MyFragmentAdapter(@NonNull FragmentManager fm, List list, List titles) {
super(fm);
this.list = list;
this.titles = titles;
}
@NonNull
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
//返回与viewpage关联以后的tablayot的内容
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
}