一、按钮触发事件写法一

  1. public class A extends AppCompatActivity {
  2. @Override
  3. protected void onCreate (Bundle saveInstanceState) {
  4. super.onCreate(saveInstanceState);
  5. Button button = findViewById(R.id.button);
  6. button.setOnClickListener(new View.OnClickListener () {
  7. @Override
  8. public void onClick (View v) {
  9. // ....
  10. }
  11. });
  12. }
  13. }

二、按钮触发事件写法二

  1. public class A extends AppCompatActivity implementes View.OnClickListener{
  2. @Override
  3. protected void onCreate (Bundle saveInstanceState) {
  4. super.onCreate(saveInstanceState);
  5. Button button = findViewById(R.id.button);
  6. button.setOnClickListener(this);
  7. }
  8. @Override
  9. public void onClick (View v) {
  10. switch (v.getId()) {
  11. case R.id.button:
  12. // ...
  13. break;
  14. case R.id.button_2:
  15. // ...
  16. break;
  17. default:
  18. }
  19. }
  20. }

三、设置按钮不可点击

  1. Button btn = findViewById(R.id.btn);
  2. btn.setEnabled(false); // false 不可点击,默认 true 可点击