這些天的開發(fā)中需要用到PullToRefreshScrollView嵌套recyclerview,代碼寫完之后發(fā)現(xiàn)了幾個(gè)問題:
- 滑動(dòng)出現(xiàn)了沖突,沒有滑動(dòng)慣性了,
- 在當(dāng)前頁(yè)面跳轉(zhuǎn)到其他頁(yè)面,再回到當(dāng)前頁(yè)面的時(shí)候recyclerview會(huì)自動(dòng)滑動(dòng)到頂端,
針對(duì)以上問題我也找到了相應(yīng)的解決方法:
1、解決滑動(dòng)的沖突:
在網(wǎng)上找的方法是通過事件分發(fā)機(jī)制,自定義ScrollView解決,
public boolean onInterceptTouchEvent(MotionEvent e) {
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downX = (int) e.getRawX();
downY = (int) e.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int moveY = (int) e.getRawY();
if (Math.abs(moveY - downY) > mTouchSlop) {
return true;
}
}
return super.onInterceptTouchEvent(e);
}
因?yàn)槲沂褂昧说谌絇ullToRefreshScrollView,如果自定義的話需要繼承這個(gè)類,But在這個(gè)pulltorefreshBase這個(gè)類里面已經(jīng)將此方法寫成final,也就是我們沒法重寫了。

經(jīng)過一般查找資料后又有了新的發(fā)現(xiàn),
在使用recyclerview的時(shí)候會(huì)用到LayoutManager,此時(shí)我們只需要將LayoutManager里面的滑動(dòng)給關(guān)閉掉,也就是返回false即可,這樣就可以解決了沖突引起的失去慣性。
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),2){
@Override
public boolean canScrollVertically()
{
return false;
}
};
rv_classify_content.setLayoutManager(gridLayoutManager);
2、解決RecyclerView自動(dòng)滑動(dòng)到頂端的問題
進(jìn)入頁(yè)面自動(dòng)跳轉(zhuǎn)到recyclerView最頂端,頁(yè)面會(huì)自動(dòng)滾動(dòng)貌似是RecyclerView 自動(dòng)獲得了焦點(diǎn),
這里的解決方法也很簡(jiǎn)單,就是RecyclerView去焦點(diǎn)。有兩種辦法:
recyclerview.setFocusableInTouchMode(false);
recyclerview.requestFocus();
或者在布局XML文件中,scrollview里面的第一層LinearLayout添加descendantFocusability屬性如下:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
這樣寫完后兩個(gè)問題都解決了。
這里補(bǔ)充一下:
descendantFocusability屬性是當(dāng)一個(gè)為view獲取焦點(diǎn)時(shí),定義viewGroup和其子控件兩者之間的關(guān)系。
屬性的值有三種:
- beforeDescendants:viewgroup會(huì)優(yōu)先其子類控件而獲取到焦點(diǎn)
- afterDescendants:viewgroup只有當(dāng)其子類控件不需要獲取焦點(diǎn)時(shí)才獲取焦點(diǎn)
- blocksDescendants:viewgroup會(huì)覆蓋子類控件而直接獲得焦點(diǎn)
總結(jié):以上是我在開發(fā)中遇到的問題,記錄下來(lái)希望對(duì)大家有幫助,如果有不同觀點(diǎn)和想法的朋友們也可以在評(píng)論中指點(diǎn)出來(lái)。