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/on_click_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="点击事件"
android:textColor="@color/black"
android:textSize="17sp"
></Button>
<Button
android:id="@+id/btn_click_single"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="点击事件"
android:textColor="@color/black"
android:textSize="17sp"
></Button>
</LinearLayout>
点击事件
package com.example.chapter03;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tv_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_view);
tv_result = findViewById(R.id.on_click_button);
Button btn_click_single = findViewById(R.id.btn_click_single);
btn_click_single.setOnClickListener(new MyOnClickListener(tv_result));
}
static class MyOnClickListener implements View.OnClickListener {
private final TextView tv_result;
public MyOnClickListener(TextView tv_result) {
this.tv_result = tv_result;
}
@Override
public void onClick(View v) {
String desc = String.format("%s 您点击了按钮:%s", 123, ((Button) v).getText());
tv_result.setText(desc);
}
}
}