回调机制和监听机制的区别、基于回调的事件传播
新建一个类MyButton
package com.example.scrollview.widget; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.Button; import androidx.appcompat.widget.AppCompatButton; public class MyButton extends AppCompatButton { public MyButton(Context context) { super(context); } public MyButton(Context context, AttributeSet attrs) { super(context, attrs); } public MyButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: Log.d("MyButton","--onTouchEvent--"); break; } return false; } }然后在Activity中也声明 onTouchEvent方法
public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: Log.d("Activity","--onTouchEvent--"); break; } return false; }当触摸按钮的时候的效果如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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=".EventActivity" android:orientation="vertical" android:padding="15dp"> <Button android:id="@+id/bt_event1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click me" android:textSize="20sp" android:onClick="show"/> <com.example.scrollview.widget.MyButton android:id="@+id/mbt1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="回调"/> </LinearLayout>会看到两个方法都响应了
打印出的日志结果为下:
在MyButton的onTouchEvent方法中调用完之后return true就是 标志着不需要再向外部回调了,所以Activity的onTouchEvent方法就不会被回调了。
如果有三个相同事件需要回调,即再在组件上添加一个时间监听器
mbt.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction()){ case MotionEvent.ACTION_DOWN: Log.d("Listener","--onTouchEvent--"); break; } return false; } });看一下执行后的效果: