利用直接绑定标签的方式实现按钮的单击事件处理,单击按钮完成Toast弹框功能。
实现代码:
MainActivity:
package com.example.zhijiebd;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button mButn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButn=(Button)findViewById(R.id.mBtn);
mButn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"监听事件处理执行了!",Toast.LENGTH_SHORT).show();
}
});
}
public void clickEventHandler(View view){
Toast.makeText(this,"绑定到标签的事件处理执行了!",Toast.LENGTH_SHORT).show();
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mBtn"
android:onClick="clickEventHandler"
android:text="直接绑定"/>
</RelativeLayout>
实验代码: