美文网首页
事件冲突

事件冲突

作者: 爱码士平头哥 | 来源:发表于2017-03-15 15:03 被阅读54次

    事件冲突在日常开中会经常碰到,比如滑动冲突 、点击事件冲突等等。常见的如ScrollView中嵌套ListView、ListView中的OnItemClickListsener监听和checkbox点击事件冲突等等。

    那么就讲它们拿来看看吧,

    例1:ScrollView 嵌入Listview,Listview的数据会显示不全。

    冲突的两种解决方案:

    一:自定义一个Listview 重写它的OnMeasure方法。

    直接上代码:

    public classMyListViewextendsListView {

    publicMyListView(Context context,AttributeSet attrs) {

    super(context,attrs);

    }

    @Override

    protected voidonMeasure(intwidthMeasureSpec, intheightMeasureSpec) {

    //关键代码

    //将高度重新测量。MeasureSpec是给的AT_MOST  ,就是WRAP_CONTENT  

    intexpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,

    MeasureSpec.AT_MOST);

    super.onMeasure(widthMeasureSpec,heightMeasureSpec);

    }

    }

    那么它好不好呢?看需求。有的是要求列表全部展开,这个时候冲突解决了,ListView数据也全部显示出来,那么需求是另一种呢?就是数据很多的情况下,需要分页。我们需要Listview 下拉加载呢??是不是懵逼了?别急,来看另外一种解决方案

    二:利用事件的拦截机制

    看代码:(也很简单)

    ListView listView = (ListView) findViewById(R.id.listView);

    ScrollView scrollView=(ScrollView)findViewById(R.id.scrollView);

    listView.setAdapter(arrayAdapter);

    listView.setOnTouchListener(newView.OnTouchListener() {

    @Override

    public booleanonTouch(View view,MotionEvent motionEvent) {

    //关键代码 

    scrollView.requestDisallowInterceptTouchEvent(true);

    return false;

    }

    });

    这里,我觉得有必要来对requestDisallowInterceptTouchEvent进行简单的介绍一下,requestDisallowInterceptTouchEvent 是ViewGroup类中的一个公用方法,参数是一个boolean值,官方介绍如下

    Called when a child does not want this parent and its ancestors to intercept touch events withViewGroup.onInterceptTouchEvent(MotionEvent).

    This parent should pass this call onto its parents. This parent must obey this request for the duration of the touch (that is, only clear the flag after this parent has received an up or a cancel.

    android系统中,一次点击事件是从父view传递到子view中,每一层的view可以决定是否拦截并处理点击事件或者传递到下一层,如果子view不处理点击事件,则该事件会传递会父view,由父view去决定是否处理该点击事件。在子view可以通过设置此方法去告诉父view不要拦截并处理点击事件,父view应该接受这个请求直到此次点击事件结束。

    这里就是调用requestDisallowInterceptTouchEvent(true),致使所有父ViewGroup跳过onInterceptTouchEvent回调。

    例2:Listview中的CheckBox选中会导致OnItemOnclickListener无效

    这里仅仅是一个焦点优先级的问题,只需在checkbox属性给一个Focusable=false即可,也可以让Listview优先获取焦点。

    相关文章

      网友评论

          本文标题:事件冲突

          本文链接:https://www.haomeiwen.com/subject/blvlnttx.html