我們講結合setOnClickListener和setOnTouchListener以及setEnabled和setClickable的相互影響。
以及View遮蓋是否能穿透事件進行分析闡述。
首先我們搞一個佈局:
<?xml version="1.0" encoding="utf-8"?>
<com.example.airy.click.R1
android:id="@+id/r1"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.airy.click.MainActivity">
<ImageView
android:id="@+id/im1"
android:background="#123123"
android:layout_width="100dp"
android:layout_height="100dp" />
<ImageView
android:id="@+id/im2"
android:alpha="0.5"
android:background="#afd1c1"
android:layout_width="200dp"
android:layout_height="200dp" />
</com.example.airy.click.R1>
m2位於m1的上層且比m1更大。兩者都在一個自定義的R1 extends RelativeLayout中。
首先場景1
二者都註冊setOnClickListener。結果是m2可以觸發,m1不可以。這很簡單。
場景2
如果我們不希望m2被點擊,那麼我們在場景1的基礎上
imageView2.setEnabled(false);
我們測試發現,m2的點擊不會觸發,m1同樣也不會。
場景3
imageView2.setClickable(false);
使用這種方式解除m2的點擊,
我們測試發現m2所覆蓋下的m1區域是可以被觸發點擊的。
實戰場景
【如果我們需要上層覆蓋VIEW不可被點擊並且要將點擊事件穿透下去,我們選用setClickable方法】
如果我們需要上層覆蓋VIEW不可被點擊並且不需要將點擊事件穿透下去,我們選用setEnabled方法】
接下來
場景4
我們給m2追加註冊setOnTouchListener事件。並且禁止setClickable
imageView2.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
showtoast("onTouch22");
return true;
}
});
imageView2.setClickable(false);
結果是如果OnTouchListener return ture那麼事件會被m2吃掉。m1點擊事件不會穿透,如果return false那麼事件將會穿透m1會觸發點擊。但是對於m2的setOnTouchListener只能接受到一個down事件並不能接收到完整的事件序列。
場景5
基於場景4變爲
imageView2.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
showtoast("onTouch22");
return true;
}
});
imageView2.setEnabled(false);
測試結果,無論retrun true和false,setOnClickListener和setOnTouchListener方法都不會被調用,m1也接受不到任何事件。
實戰場景
【VIEW不可被點擊並且setOnTouchListener不被調用且事件不穿透下去可以使用setEnabled】
知識點比較基礎,但再項目實戰中相對實用。從view事件分發的角度確實也可以解釋這幾個現象,最近博主也是在做一個廣告浮層類似的東西總結出的經驗和大家分享。
哪裏可以找到我:
我的Github: https://github.com/AndroidMsky
我的博客主頁: http://blog.csdn.net/androidmsky
歡迎加作者自營安卓開發交流羣:
308372687