Android学习笔记5-2
推荐新手向学习视频:B站https://www.bilibili.com/video/av38409964点我传送
5-2 基于回调事件的处理机制
-
先执行自定义控件里的回调,再执行Activity里的回调。事件由控件本身向Activity传播,要return false
return false;//表示这个事件我处理了,但没有消费掉,可以继续传播 return true;//表示这个事件到此为止,我已经全部搞完了,被消费掉了
-
监听优先于回调
-
EventActivity.java
package com.ylw.helloworld; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import com.ylw.helloworld.util.ToastUtil; import com.ylw.helloworld.widget.MyButton; public class EventActivity extends AppCompatActivity { private Button mBtnEvent; private MyButton btnMy; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event); mBtnEvent = findViewById(R.id.btn_event); btnMy = findViewById(R.id.btn_my); btnMy.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: Log.d("Listener","---onTouch---"); break; } return false; } }); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: Log.d("Activity","---onTouchEvent---"); break; } return false; } }
-
自定义控件MyButton.java
package com.ylw.helloworld.widget; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; 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) { //onTouchEvent包含很多动作 super.onTouchEvent(event); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: Log.d("MyButton","---onTouchEvent---"); break; } return false;//表示这个事件我处理了,但没有消费掉,可以继续传播 //return true;//表示这个事件到此为止,我已经全部搞完了,被消费掉了 } }
-
activity_event.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/btn_event" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="click me" android:textAllCaps="false" android:onClick="show"/> <com.ylw.helloworld.widget.MyButton android:id="@+id/btn_my" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="my button" android:textAllCaps="false"/> </LinearLayout>
-
效果,通过日志打印可以看出来执行顺序,这里就不展示了。