1.如何使用ViewPager2
implementation 'com.google.android.material:material:1.2.0-alpha06'
2.在布局文件中添加
3.创建适配器
public class ViewPager2Adapter extends FragmentStateAdapter {
private List fLists = new ArrayList<>();
public ViewPager2Adapter(@NonNull FragmentActivity fragmentActivity, List fLists) {
super(fragmentActivity);
this.fLists = fLists;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fLists.get(position);
}
@Override
public int getItemCount() {
return fLists.size();
}
}
然后再MainActivity中
List fLists = new ArrayList<>();
fLists.add(new HomeFragment());
fLists.add(new FaberFragment());
fLists.add(new DealFragment());
fLists.add(new ContractFragment());
fLists.add(new AssetFragment());
ViewPager2Adapter adapter = new ViewPager2Adapter(this, fLists);
mBinding.vp2.setAdapter(adapter);
mBinding.vp2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
mBinding.bnv.getMenu().getItem(position).setChecked(true);
}
});
mBinding.bnv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_hone:
mBinding.vp2.setCurrentItem(0);
return true;
case R.id.menu_faber:
mBinding.vp2.setCurrentItem(1);
return true;
case R.id.menu_deal:
mBinding.vp2.setCurrentItem(2);
return true;
case R.id.menu_contract:
mBinding.vp2.setCurrentItem(3);
return true;
case R.id.menu_asset:
mBinding.vp2.setCurrentItem(4);
return true;
}
return false;
}
});
在单独使用ViewPager2的时候我们发现具有懒加载效果,但是当我们结合tablayout使用的时候却是滑动ViewPager2的时候是懒加载效果,但当我们点击的时候发现没有懒加载效果,这并不是我们想要的,解决方法在点击的时候设置setCurrentItem(position)的时候要加上false setCurrentItem(position,false); 就实现了懒加载效果