布局。。。需要导design的包
activity中的代码块
public class MainActivity extends AppCompatActivity {
private ViewPager pager;
private ArrayList list;
private TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.table);
pager = findViewById(R.id.view_pager);
//第四部:写页面
list = new ArrayList<>();
list.add(new fragment());
list.add(new fragment1());
//第五步 导航栏数据
String [] str={"首页","我的"};
MyAdapter myAdapter=new MyAdapter(getSupportFragmentManager(), list,str);
pager.setAdapter(myAdapter);
//关联方法
tabLayout.setupWithViewPager(pager);
}
}
Adapter中的代码
public class MyAdapter extends FragmentPagerAdapter {
private ArrayList list;
private String[] str;
public MyAdapter(FragmentManager fm, ArrayList list, String[] str) {
super(fm);
this.list = list;
this.str = str;
}
@Override
public Fragment getItem(int i) {
return list.get(i);
}
@Override
public int getCount() {
return list.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
//返回数组
return str[position];
}