事件处理有三种方法:
#主页面的XML文件,点击不同按钮展示不同的情况
<?xml version="1.0" encoding="utf-8"?>
<net.onest.eventhandlech0301.MyLinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >
<Button
android:id="@+id/btn_normal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="普通的按钮"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et"/>
<Button
android:id="@+id/btn_click"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="buttonClicked"
android:text="事件监听器按钮"/>
<net.onest.eventhandlech0301.MyButton
android:id="@+id/btn_custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="自定义触摸事件回调方法的按钮"/>
<net.onest.eventhandlech0301.MyImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ball"/>
</net.onest.eventhandlech0301.MyLinearLayout>
1.基于监听
直接通过组件的引用.setXXX的方法设置监听
//对输入框的键盘事件做处理
EditText editText = findViewById(R.id.et);
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
//KeyEvent键盘事件类型
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.e("输入框的按键事件处理方法",event.getNumber() + "");//获取数字按钮的值
return false;
}
});
Button btnNormal = findViewById(R.id.btn_normal);
btnNormal.setOnClickListener(this);//MainActivity作为监听器
btnNormal.setOnTouchListener(new View.OnTouchListener() {
@Override
//对触摸事件的处理
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction())