Android studio 建立一个新的项目,修改XML如下:
其中Activity名称为:MyOnClikEvent
<?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"
android:orientation="vertical"
android:gravity="center"
tools:context=".MyOnClikEvent">
<Button
android:id="@+id/btn_clik0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="内部类实现单击按钮"/>
<Button
android:id="@+id/btn_clik1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="匿名内部类实现单击按钮"/>
<Button
android:id="@+id/btn_clik2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btnClik"
android:text="xml方法回调实现单击按钮"/>
<Button
android:id="@+id/btn_LongClik"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="长按按钮实现单击按钮"/>
</LinearLayout>
修改Activity如下:
package com.example.mtlayoutactivity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MyOnClikEvent extends AppCompatActivity {
Button btn0;
Button btn1;
//接口实现单击按钮,一个类只实现一个单击事件,不在此类中实现
Button btn2;//xml方法回调实现单击按钮
Button btnLong;
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_on_clik_event);
//查找XML中的Button的id
btn0 = findViewById(R.id.btn_clik0);
//MyClik自己写的内部类方法
btn0.setOnClickListener(new MyClik());
//查找XML中的Button的id
btn1 = findViewById(R.id.btn_clik1);
//匿名内部类实现按钮单击
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn1.setText("单击了匿名内部类实现按钮单击" + String.valueOf(i++));
}
});
//查找XML中的Button的id
btnLong = findViewById(R.id.btn_LongClik);
//匿名内部类实现按钮长按
btnLong.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
btnLong.setText("长安实现按钮点击" + String.valueOf(i++));
return false;
}
});
}
//内部类实现的按钮单击
//implements 使生效
public class MyClik implements View.OnClickListener {
public void onClick(View v) {
btn0.setText("单击了内部类实现的按钮单击" + String.valueOf(i++));
}
}
public void btnClik(View V) {
//查找XML中的Button的id
btn2 = findViewById(R.id.btn_clik2);
btn2.setText("单击了xml方法回调实现单击按钮单击" + String.valueOf(i++));
}
}
运行界面如下:
按钮文本显示的修改,int类型变量转化为String类型。
btn2.setText("单击了xml方法回调实现单击按钮单击" + String.valueOf(i++));