Android在RecyclerView中巢狀ScrollView,解決兩者間的滑動衝突
阿新 • • 發佈:2019-01-25
在RecyclerView中的item中巢狀一些佈局如TextView,在這種情況下如TextView的字數很多超過所設定的佈局大小。
這樣就需要在item中加一個ScrollView可以用於使用者的滑動。
1.RecyclerView的item佈局如:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.administrator.textscrollview.TextScrollView android:layout_width="wrap_content" android:fadeScrollbars="false" android:layout_height="120dp"> <TextViewandroid:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content"/></com.example.administrator.textscrollview.TextScrollView> </LinearLayout>
加入可顯示的滾動條
2.自定義一個繼承RecyclerView的view,在onIntercptTouchEvent對觸控事件強制不攔截:
package com.example.administrator.textscrollview; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet;3.自定義一個繼承ScrollView的view,對從父控制元件傳下來的事件進行處理:import android.view.MotionEvent; /** * @author wangyao * @package com.example.administrator.textscrollview * @date 2018/1/11 15:52 * @describe TODO * @project */ public class MyListView extends RecyclerView { public MyListView(Context context) { super(context); } public MyListView(Context context, AttributeSet attrs) { super(context, attrs); } public MyListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return false; } }
package com.example.administrator.textscrollview; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ScrollView; /** * @author wangyao * @package com.example.administrator.textscrollview * @date 2018/1/11 15:42 * @describe TODO * @project */ public class TextScrollView extends ScrollView { private float mCurrentMoveY = 0; private float mProMoveY = 0; public TextScrollView(Context context) { super(context); } public TextScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public TextScrollView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: { mProMoveY = ev.getY(); } break; case MotionEvent.ACTION_MOVE: { mCurrentMoveY = ev.getY(); this.scrollBy(0, (int) (mProMoveY - mCurrentMoveY)); mProMoveY = mCurrentMoveY; } break; case MotionEvent.ACTION_UP: { } break; } if (canScroll()) { return true; }else { return false; } } /** * 判斷TextScrollView裡面包裹的內容是否可以滾動 * @return */ private boolean canScroll() { View childAt = getChildAt(0); if (childAt != null) { int height = childAt.getHeight(); return getHeight() < height; } return false; } }