三种方式包括在布局文件中指定onClick属性的值;使用匿名内部类;使用接口。
注:一般按钮较多建议使用第三种
效果图:
在xml内设置三个垂直排列的Button
<?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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:padding="20dp" >
<Button
android:id="@+id/bnt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮1"
android:onClick="click" />
<Button
android:id="@+id/bnt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮2"
android:onClick="click"/>
<Button
android:id="@+id/bnt3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮3"
android:onClick="click"/>
</LinearLayout>
在java界面分别使用三种不同的方式实现点击事件
package com.example.button;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button1, button2, button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.bnt1);
button2 = findViewById(R.id.bnt2);
button3 = findViewById(R.id.bnt3);
//按钮2使用的是匿名内部类
button2.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
button2.setText("按钮2已经被点击");
}
});
//按钮3使用的是接口
button3.setOnClickListener(this) ;
}
@Override
public void onClick(View view) {
Toast.makeText(MainActivity .this,"按钮3已经被点击",Toast.LENGTH_LONG ).show();
}
//按钮3的使用的是和按钮1和按钮2不一样的实现点击事件的代码。按钮1和2是直接在在按钮上改变而按钮3是在页面下面的短暂的提示
//按钮1使用的是按属性的
public void click (View view){
button1.setText("按钮1已经被点击");
}
}