
面試的時(shí)候,筆者說(shuō)出的方案是:上面用自定義控件,下面單用一個(gè)ViewPager來(lái)實(shí)現(xiàn),但面試官認(rèn)為單用一個(gè)ViewPager難以實(shí)現(xiàn),需用兩個(gè)ViewPager進(jìn)行嵌套,當(dāng)時(shí)我心里也沒(méi)多少底,畢竟后來(lái)很少玩UI控件了,回來(lái)后,我特意嘗試了兩種不同的實(shí)現(xiàn)方案,特此記錄!
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中每一個(gè)Fragment,布局也同上,如此嵌套,確實(shí)能夠?qū)崿F(xiàn)多層Tab級(jí)聯(lián)的效果,直接上代碼:
Activity的關(guān)鍵代碼:
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);//注意:特意設(shè)置預(yù)加載
viewPager.setAdapter(new MainHomePagerAdapter(getSupportFragmentManager(),menu,list));
tabLayout.setupWithViewPager(viewPager);
ViewPagerFragment的關(guān)鍵代碼:
String[] menu={"內(nèi)層"+index+"A", "內(nèi)層"+index+"B","內(nèi)層"+index+"C","內(nèi)層"+index+"D","內(nèi)層"+index+"E","內(nèi)層"+index+"F","內(nèi)層"+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就是下面展示內(nèi)容的,沒(méi)什么好說(shuō)的,就不貼代碼了。
請(qǐng)注意一下Activity關(guān)鍵代碼中的唯一一個(gè)注釋,這里之所以要設(shè)置外層ViewPager預(yù)加載,是因?yàn)槿绻辉O(shè)置這個(gè)的話,外層ViewPager從位置0跳到位置2,再返回位置1,會(huì)報(bào)如下的錯(cuò)誤:
java.lang.IllegalStateException: Fragment no longer exists for key f0: index 0
網(wǎng)上查了一圈(詳情可參考這里),這是由于ViewPager嵌套,出現(xiàn)Fragment被銷毀導(dǎo)致的,相關(guān)報(bào)錯(cuò)與FragmentStatePagerAdapter中下面兩個(gè)方法有關(guān),可以通過(guò)覆蓋重寫下面兩個(gè)方法來(lái)解決問(wèn)題,但經(jīng)筆者試驗(yàn),最簡(jiǎn)單的就是設(shè)置預(yù)加載,以此防止Fragment被銷毀。
@Override
public Parcelable saveState() {
return super.saveState();
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
super.restoreState(state, loader);
}
至此,這種方案大概也就這樣子的,畢竟容易實(shí)現(xiàn),當(dāng)然,由于使用了ViewPager嵌套,肯定多少會(huì)存在部分性能問(wèn)題,但好處是易想易做,筆者猜測(cè)網(wǎng)易云音樂(lè)首頁(yè)類似的效果應(yīng)該也是采用了該方案的。
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直接嵌套了最終的內(nèi)容:ContentFragment,Activity的關(guān)鍵代碼如下:
//定義的成員變量
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={"內(nèi)層"+i+"A", "內(nèi)層"+i+"B","內(nèi)層"+i+"C","內(nèi)層"+i+"D","內(nèi)層"+i+"E","內(nèi)層"+i+"F","內(nèi)層"+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);
//監(jiān)聽tabLayout1變化,根據(jù)變化相應(yīng)刷新tabLayout2的內(nèi)容
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();//設(shè)置選中第一個(gè)
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//監(jiān)聽viewPager的變化,在滑到最前或最后時(shí),判斷是否進(jìn)行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){
//滑動(dòng)到最后一頁(yè)繼續(xù)往后滑
if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1) {
int tabPosition = tabLayout1.getSelectedTabPosition();
if(tabPosition!= menuList.size()-1){//不是最后一個(gè)
tabLayout1.getTabAt(tabPosition+1).select();
}
}else if(viewPager.getCurrentItem() == 0) { //滑動(dòng)到第一頁(yè)繼續(xù)往前滑
int tabPosition = tabLayout1.getSelectedTabPosition();
if(tabPosition!= 0){//不是第一個(gè)
tabLayout1.getTabAt(tabPosition-1).select();
}
}
}
misScrolled = true;
break;
}
}
});
該方案的重點(diǎn)在于將Tab內(nèi)及Fragment進(jìn)行分組,也就是:List<List<String>> menuList和List<List<BaseFragment>> fragmentlist,這是為了配合下面Tab級(jí)聯(lián)實(shí)現(xiàn)的,然后監(jiān)聽TabLayout和ViewPager的選中和滑動(dòng)動(dòng)作,以此實(shí)現(xiàn)級(jí)聯(lián)滑動(dòng)的效果。
注意到其中監(jiān)聽tabLayout1變化后,重新刷新tabLayout2的相關(guān)內(nèi)容時(shí),筆者注釋掉的那行代碼:viewPager.setAdapter,因?yàn)楣P者一開始發(fā)現(xiàn) adapter.notifyDataSetChanged()失效了,無(wú)法刷新內(nèi)容,所以才用了直接綁定數(shù)據(jù)的方案,但這明顯不科學(xué)啊,后經(jīng)查證發(fā)現(xiàn),其實(shí)解決方案非常簡(jiǎn)單,只需覆蓋一下PagerAdapter中的方法(詳情可參考這里):
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
至此,改方案也大概就是這樣子了,事實(shí)證明,只使用單層ViewPager也能實(shí)現(xiàn)多層Tab級(jí)聯(lián)的效果。該方案結(jié)構(gòu)布局方面比較簡(jiǎn)單,不用嵌套ViewPager,性能上有一定的優(yōu)勢(shì)。缺點(diǎn)在于:利用監(jiān)聽ViewPager的方式來(lái)實(shí)現(xiàn)外層Tab的切換的,所以在切換時(shí)無(wú)法像多層ViewPager嵌套那樣進(jìn)行預(yù)覽,故切換略顯突兀。
多想多動(dòng)手,總會(huì)有所收獲的!