Android事件分发<一>

Android事件分发一直是硬伤,项目中不断出现各种View滑动冲突所以想研究一下彻底的了解android事件分发。
先来了解一下事件的分发主要有以下几个方法:

public boolean dispatchTouchEvent(MotionEvent ev)
public boolean onTouchEvent(MotionEvent event) 
public boolean onInterceptTouchEvent(MotionEvent ev)

先不介绍功能了就单纯的看看当我们点击一个LinearLayout的事件是如何传递的这是布局文件

<?xml version="1.0" encoding="utf-8"?>
<com.example.androiddishpahevents.views.LinearoutOne xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:padding="30dp">
    <com.example.androiddishpahevents.views.LinearoutTwo
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        android:orientation="vertical"
        android:padding="40dp">
        <com.example.androiddishpahevents.views.LinearoutThree
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1.0"
            android:background="@color/colorPrimaryDark"
            android:gravity="center">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="事件分发啊啊"
                android:textColor="@android:color/darker_gray" />
        </com.example.androiddishpahevents.views.LinearoutThree>
    </com.example.androiddishpahevents.views.LinearoutTwo>
</com.example.androiddishpahevents.views.LinearoutOne>

试图界面如下:

这里写图片描述

LinearOutOne里面包含LinearTwo,
LinearOutTwo中包含LinearOutThree,
LinearOutThree中包含一个TextView。

暂时不对TextView做点击监听和ontouch监听,当我们点击LinearOutThree时看事件是如何分发的,我们分别重写了LinearoutOne,LinearoutTwo,LinearoutThree的上面那三个方法,和MainActivity中的

public boolean dispatchTouchEvent(MotionEvent ev)
public boolean onTouchEvent(MotionEvent event) 

这两个方法。看一下具体的运行点击LinearOutThree的事件分发。

这里写图片描述

有图示就不啰嗦了,我把图里面的内容摘取出来看的清楚一些:

//当我们按下屏幕的时候的事件分发
MainActivity-----dispatchTouchEvent
LinearoutOne-----dispatchTouchEvent
LinearoutOne-----onInterceptTouchEvent
LinearoutTwo-----dispatchTouchEvent
LinearoutTwo-----onInterceptTouchEvent
LinearoutThree-----dispatchTouchEvent
LinearoutThree-----onInterceptTouchEvent
LinearoutThree-----dispatchTouchEvent
LinearoutTwo-----onTouchEvent
LinearoutOne-----onTouchEvent
MainActivity-----onTouchEvent

//当我们手指离开屏幕时的事件分发
MainActivity-----dispatchTouchEvent
MainActivity-----onTouchEvent

小结一下:
事件是逐级下传,Mainactiviy获取点击事件下传给子布局,子布局再往下下传,下传到被点击的view,之后再往上回传。先是dispatchTouchEvent分发,之后onTouchEvent回传。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值