面试的时候,笔者说出的方案是:上面用自定义控件,下面单用一个ViewPager来实现,但面试官认为单用一个ViewPager难以实现,需用两个ViewPager进行嵌套,当时我心里也没多少底,毕竟后来很少玩UI控件了,回来后,我特意尝试了两种不同的实现方案,特此记录!
1、多层ViewPager嵌套方案
直接上布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.activity.demo.MyViewPagerActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="46dp"
android:layout_gravity="bottom"
android:background="@color/color_white"
app:tabSelectedTextColor="@color/THEME_BLUE">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</LinearLayout>
该方案Activity采用的是TabLayout+ViewPager,然后ViewPager中每一个Fragment,布局也同上,如此嵌套,确实能够实现多层Tab级联的效果,直接上代码:
Activity的关键代码:
String[] menu={"外层0", "外层1", "外层2"};
List<BaseFragment> list=new ArrayList<>();
for(int i=0;i<menu.length;i++){
ViewPagerFragment viewPagerFragment=new ViewPagerFragment();
Bundle bundle = new Bundle();
bundle.putInt("index",i);
viewPagerFragment.setArguments(bundle);
list.add(viewPagerFragment);
}
viewPager.setOffscreenPageLimit(2);//注意:特意设置预加载
viewPager.setAdapter(new MainHomePagerAdapter(getSupportFragmentManager(),menu,list));
tabLayout.setupWithViewPager(viewPager);
ViewPagerFragment的关键代码:
String[] menu={"内层"+index+"A", "内层"+index+"B","内层"+index+"C","内层"+index+"D","内层"+index+"E","内层"+index+"F","内层"+index+"G"};
List<BaseFragment> list=new ArrayList<>();
for(int i=0;i<menu.length;i++){
ContentFragment contentFragment=new ContentFragment();
Bundle bundle = new Bundle();
bundle.putString("content",menu[i]);
contentFragment.setArguments(bundle);
list.add(contentFragment);
}
viewPager.setAdapter(new MainHomePagerAdapter(getChildFragmentManager(),menu,list));
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
其中,MainHomePagerAdapter继承于FragmentStatePagerAdapter,代码如下:
public class MainHomePagerAdapter extends FragmentStatePagerAdapter {
private String[] menu;
private List<BaseFragment> list;
public MainHomePagerAdapter(FragmentManager fm, String[] menu, List<BaseFragment> list) {
super(fm);
this.menu=menu;
this.list=list;
}
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return menu.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return menu[position];
}
而ContentFragment就是下面展示内容的,没什么好说的,就不贴代码了。
请注意一下Activity关键代码中的唯一一个注释,这里之所以要设置外层ViewPager预加载,是因为如果不设置这个的话,外层ViewPager从位置0跳到位置2,再返回位置1,会报如下的错误:
java.lang.IllegalStateException: Fragment no longer exists for key f0: index 0
网上查了一圈(详情可参考这里),这是由于ViewPager嵌套,出现Fragment被销毁导致的,相关报错与FragmentStatePagerAdapter中下面两个方法有关,可以通过覆盖重写下面两个方法来解决问题,但经笔者试验,最简单的就是设置预加载,以此防止Fragment被销毁。
@Override
public Parcelable saveState() {
return super.saveState();
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
super.restoreState(state, loader);
}
至此,这种方案大概也就这样子的,毕竟容易实现,当然,由于使用了ViewPager嵌套,肯定多少会存在部分性能问题,但好处是易想易做,笔者猜测网易云音乐首页类似的效果应该也是采用了该方案的。
2、单层ViewPager方案
也是直接上布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.activity.demo.MyViewPagerActivity2">
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout1"
android:layout_width="match_parent"
android:layout_height="46dp"
android:layout_gravity="bottom"
android:background="@color/color_white"
app:tabSelectedTextColor="@color/THEME_BLUE">
</android.support.design.widget.TabLayout>
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout2"
android:layout_width="match_parent"
android:layout_height="46dp"
android:layout_gravity="bottom"
android:background="@color/color_white"
app:tabSelectedTextColor="@color/THEME_BLUE">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</LinearLayout>
该方案Activity使用的是两层TabLayout+单层ViewPager,ViewPager直接嵌套了最终的内容:ContentFragment,Activity的关键代码如下:
//定义的成员变量
private List<List<String>> menuList;
private List<List<BaseFragment>> fragmentlist;
private MainHomePagerAdapter adapter;
private boolean misScrolled=false;
String[] menu1={"外层0", "外层1", "外层2"};
menuList = new ArrayList<>();
fragmentlist = new ArrayList<>();
for(int i=0;i<menu1.length;i++){
tabLayout1.addTab(tabLayout1.newTab());
tabLayout1.getTabAt(i).setText(menu1[i]);
String[] menu2={"内层"+i+"A", "内层"+i+"B","内层"+i+"C","内层"+i+"D","内层"+i+"E","内层"+i+"F","内层"+i+"G"};
List<String> stringList = Arrays.asList(menu2);
menuList.add(stringList);
List<BaseFragment> list=new ArrayList<>();
for(int j=0;j<menu2.length;j++){
ContentFragment contentFragment=new ContentFragment();
Bundle bundle = new Bundle();
bundle.putString("content",menu2[j]);
contentFragment.setArguments(bundle);
list.add(contentFragment);
}
fragmentlist.add(list);
}
adapter = new MainHomePagerAdapter(getSupportFragmentManager(), menuList.get(0).toArray(new String[0]), fragmentlist.get(0));
viewPager.setAdapter(adapter);
tabLayout2.setupWithViewPager(viewPager);
tabLayout2.setTabMode(TabLayout.MODE_SCROLLABLE);
//监听tabLayout1变化,根据变化相应刷新tabLayout2的内容
tabLayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
//viewPager.setAdapter(new MainHomePagerAdapter(getSupportFragmentManager(), menuList.get(position).toArray(new String[0]), fragmentlist.get(position)));
adapter.setMenu(menuList.get(position).toArray(new String[0]));
adapter.setList(fragmentlist.get(position));
adapter.notifyDataSetChanged();
tabLayout2.getTabAt(0).select();//设置选中第一个
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//监听viewPager的变化,在滑到最前或最后时,判断是否进行tabLayout1的切换
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
switch (state) {
case ViewPager.SCROLL_STATE_DRAGGING:
misScrolled = false;
break;
case ViewPager.SCROLL_STATE_SETTLING:
misScrolled = true;
break;
case ViewPager.SCROLL_STATE_IDLE:
if(!misScrolled){
//滑动到最后一页继续往后滑
if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1) {
int tabPosition = tabLayout1.getSelectedTabPosition();
if(tabPosition!= menuList.size()-1){//不是最后一个
tabLayout1.getTabAt(tabPosition+1).select();
}
}else if(viewPager.getCurrentItem() == 0) { //滑动到第一页继续往前滑
int tabPosition = tabLayout1.getSelectedTabPosition();
if(tabPosition!= 0){//不是第一个
tabLayout1.getTabAt(tabPosition-1).select();
}
}
}
misScrolled = true;
break;
}
}
});
该方案的重点在于将Tab内及Fragment进行分组,也就是:List<List<String>> menuList和List<List<BaseFragment>> fragmentlist,这是为了配合下面Tab级联实现的,然后监听TabLayout和ViewPager的选中和滑动动作,以此实现级联滑动的效果。
注意到其中监听tabLayout1变化后,重新刷新tabLayout2的相关内容时,笔者注释掉的那行代码:viewPager.setAdapter,因为笔者一开始发现 adapter.notifyDataSetChanged()失效了,无法刷新内容,所以才用了直接绑定数据的方案,但这明显不科学啊,后经查证发现,其实解决方案非常简单,只需覆盖一下PagerAdapter中的方法(详情可参考这里):
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
至此,改方案也大概就是这样子了,事实证明,只使用单层ViewPager也能实现多层Tab级联的效果。该方案结构布局方面比较简单,不用嵌套ViewPager,性能上有一定的优势。缺点在于:利用监听ViewPager的方式来实现外层Tab的切换的,所以在切换时无法像多层ViewPager嵌套那样进行预览,故切换略显突兀。
多想多动手,总会有所收获的!