Android ScrollView嵌套ListView 滑动冲突问题的解决方法

1、自定义ScrollView类,处理事件分发

/**
 * 解决scrollview嵌套listview造成滑动冲突的问题
 * Created by xl on 2019/1/25.
 */
public class ListScrollView extends ScrollView {

    private ListView listView;

    public ListScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ListScrollView(Context context) {
        super(context);
    }

    /**
     * 覆写onInterceptTouchEvent方法,点击操作发生在ListView的区域的时候,
     * 返回false让ScrollView的onTouchEvent接收不到MotionEvent,而是把Event传到下一级的控件中
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (listView != null && checkArea(listView, ev)) {
            return false;
        }
        return super.onInterceptTouchEvent(ev);
    }

    /**
     * 测试view是否在点击范围内
     *
     * @param v
     * @return
     */
    private boolean checkArea(View v, MotionEvent event) {
        float x = event.getRawX();
        float y = event.getRawY();
        int[] locate = new int[2];
        v.getLocationOnScreen(locate);
        int l = locate[0];
        int r = l + v.getWidth();
        int t = locate[1];
        int b = t + v.getHeight();
        if (l < x && x < r && t < y && y < b) {
            return true;
        }
        return false;
    }

    public ListView getListView() {
        return listView;
    }

    public void setListView(ListView listView) {
        this.listView = listView;
    }

}

2、xml布局文件中使用

<add.ds.com.view.ListScrollView
        android:id="@+id/scrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/action_bar_margin"
        android:layout_marginRight="@dimen/action_bar_margin"
        android:scrollbars="none">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ListView
                android:id="@+id/list1"
                android:layout_width="match_parent"
                android:layout_height="400dp"
                android:layout_marginTop="5dp"
                android:cacheColorHint="@color/transparent"
                android:divider="@color/transparent"
                android:dividerHeight="5dp"
                android:listSelector="@color/transparent" />

        </LinearLayout>

    </add.ds.com.view.ListScrollView>

3、activity中使用

private ListScrollView m_scrollView;
m_scrollView = (ListScrollView) this.findViewById(R.id.scrollview);
m_scrollView.setListView(m_listView);

完!!!

展开阅读全文

没有更多推荐了,返回首页