最近在寫新App,那么新App中使用的就是AndroidX那一套玩意了,然后嘗試了個首頁功能,Androidx viewPager + tabLayout。 結果就這點小功能就折騰了幾個小時。寫的過程中,中間也是踩了不少的坑,下面聽我詳細描述吧。
找了幾篇博客,看了下AndroidX下的代碼寫法,抄到了xml布局文件中, 布局如下:
<?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" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabBackground="@android:color/transparent" app:tabGravity="fill" app:tabIndicatorColor="@color/colorAccent" app:tabIndicatorFullWidth="true" app:tabMaxWidth="0dp" app:tabMode="fixed" app:tabRippleColor="@android:color/transparent" app:tabSelectedTextColor="@color/colorPrimary" app:tabTextColor="@color/colorPrimary" /> <View android:layout_width="match_parent" android:layout_height="0.5dp" android:background="#E4E4E4" /> <androidx.viewpager.widget.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent"> </androidx.viewpager.widget.ViewPager> </LinearLayout>
就是這樣很常規的布局,然后寫好了viewpager的adapter,以及代碼調用等
imageFragment = ImageFragment.newInstance(); fragmentList.add(imageFragment); videoFragment = VideoFragment.newInstance(); fragmentList.add(videoFragment); mainAdapter = new MainAdapter(getSupportFragmentManager()); viewPager.setAdapter(mainAdapter); tabLayout.setupWithViewPager(viewPager);
運行的結果,點擊tabLayout,切換效果一切ok,但是呢,滑動ViewPager切換,就出現了問題,tabLayout滑動的效果不對,我只有兩個title,期望的是滑動ViewPager,對應的tabItem切到另外一個,而不是在中間階段停住,網上搜索了好久,也沒找到答案。運行了幾個開源項目寫的sample,發現也如此,所以懵逼了。最后只好祭出了大招,看源碼。發現ViewPager的onPageScrolled的方法里面,有個變量很關鍵,mDecorChildCount,用來控制viewPager子View的滑動,瞬間就明白了,找到了問題所在,改了布局,運行下,效果完美。
<?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" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <androidx.viewpager.widget.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabBackground="@android:color/transparent" app:tabGravity="fill" app:tabIndicatorColor="@color/colorAccent" app:tabIndicatorFullWidth="true" app:tabMaxWidth="0dp" app:tabMode="fixed" app:tabRippleColor="@android:color/transparent" app:tabSelectedTextColor="@color/colorPrimary" app:tabTextColor="@color/colorPrimary" /> <View android:layout_width="match_parent" android:layout_height="0.5dp" android:background="#E4E4E4" /> </androidx.viewpager.widget.ViewPager> </LinearLayout>
將tabLayout放到ViewPager里面即可。