PagerAdapter是一个抽象类,它有两个实现子类供我们使用,分别是FragmentStatePagerAdapter和FragmentPagerAdapter
FragmentPagerAdapter在销毁Fragment时不会调用onDestroy()方法,而带了State的Adapter则会调用Fragment的onDestroy()方法,换言之,前者仅仅是销毁了Fragment的View视图而没有销毁Fragment这个对象,但是后者则彻彻底底地消灭了Fragment对象
FragmentPagerAdapter适用于Fragment比较少的情况,它会把每一个Fragment保存在内存中,不用每次切换的时候,去保存现场,切换回来在重新创建,所以用户体验比较好。而对于Fragment比较多的情况,需要切换的时候销毁以前的Fragment以释放内存,就可以使用FragmentStatePagerAdapter。
TabLayout+ViewPager+Fragment方法的使用流程:
创建存储多个Fragment实例的列表
创建PagerAdapter实例并关联到Viewpager中
将ViewPager关联到Tablayout中
根据需求改写Tablayout属性*
public class FragmentViewpager extends FragmentPagerAdapter {
List<Fragment> fragmentList;
List<String> stringList;
public FragmentViewpager(@NonNull FragmentManager fm,List<Fragment> fragment,List<String>stringList) {
super(fm);
this.fragmentList=fragment;
this.stringList=stringList;
}
@NonNull
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return stringList.get(position);
}
}
public class MainActivity extends AppCompatActivity {
private ViewPager viewpager;
private TabLayout tab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewpager = (ViewPager) findViewById(R.id.viewpager);
tab = (TabLayout) findViewById(R.id.tab);
ArrayList<Fragment> list = new ArrayList<>();
list.add(new FragmentOne());
list.add(new FragmentTwo());
list.add(new FragmentThree());
List<String> titles = new ArrayList<>();
titles.add("推荐");
titles.add("关注");
titles.add("附近");
FragmentViewpager myViewpager = new FragmentViewpager(getSupportFragmentManager(),list,titles);
viewpager.setAdapter(myViewpager);
tab.setupWithViewPager(viewpager);
//翻页监听
viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position){
case 0:
Toast.makeText(MainActivity.this, "1", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(MainActivity.this, "2", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(MainActivity.this, "3", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
//state的状态有三个,0表示什么都没做,1正在滑动,2滑动完毕
}
});
}
}