Android事件分发<一>

来源:互联网 发布:根据数据库生成网页 编辑:程序博客网 时间:2024/06/06 01:08

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-----dispatchTouchEventLinearoutOne-----dispatchTouchEventLinearoutOne-----onInterceptTouchEventLinearoutTwo-----dispatchTouchEventLinearoutTwo-----onInterceptTouchEventLinearoutThree-----dispatchTouchEventLinearoutThree-----onInterceptTouchEventLinearoutThree-----dispatchTouchEventLinearoutTwo-----onTouchEventLinearoutOne-----onTouchEventMainActivity-----onTouchEvent//当我们手指离开屏幕时的事件分发MainActivity-----dispatchTouchEventMainActivity-----onTouchEvent

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

0 0
原创粉丝点击