最近在Android开发中,需要在ScrollView里面嵌套ListView,嵌套之后发现滑动冲突。问google问度娘,得出的很多答案都是设置listView的高度,让所有的item都显示出来,我觉得这是一种很不好的解决办法。在试过了很多次之后,发现其实可以通过判断ListView在屏幕上的坐标,如果发生的Touch事件在ListView内,则ScrollView放弃拦截下该时间,把他传到下一层次的View (ListView)中去处理。
继承ScrollView,把ListView实例传到ScrollView中,复写ScrollView的onInterceptTouchEvent方法, 用getLocationInWindow方法获取ListView相对于屏幕的位置,调用MotionEvent的getRawX和getRawY方法获取点击事件相对于屏幕的坐标,判断该坐标是否发生在ListView的区域内,如果是,则对onInterceptTouchEvent方法直接返回false。
- package com.example.listscrollview;
- import android.content.Context;
- import android.util.AttributeSet;
- import android.view.MotionEvent;
- import android.view.View;
- import android.widget.ListView;
- import android.widget.ScrollView;
- 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) {
- // TODO Auto-generated method stub
- if (listView != null && checkArea(listView, ev)) {
- return false;
- }
- return super.onInterceptTouchEvent(ev);
- }
- /**
- * 测试view是否在点击范围内
- * @param locate
- * @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;
- }
- }