一、按钮触发事件写法一
public class A extends AppCompatActivity {
@Override
protected void onCreate (Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener () {
@Override
public void onClick (View v) {
// ....
}
});
}
}
二、按钮触发事件写法二
public class A extends AppCompatActivity implementes View.OnClickListener{
@Override
protected void onCreate (Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
Button button = findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick (View v) {
switch (v.getId()) {
case R.id.button:
// ...
break;
case R.id.button_2:
// ...
break;
default:
}
}
}
三、设置按钮不可点击
Button btn = findViewById(R.id.btn);
btn.setEnabled(false); // false 不可点击,默认 true 可点击