基本的事件监听方式

  1. package com.example.myapplication;
  2. import android.os.Bundle;
  3. import android.view.View;
  4. import android.widget.Button;
  5. import android.widget.Toast;
  6. import androidx.appcompat.app.AppCompatActivity;
  7. public class LineList extends AppCompatActivity {
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.activity_line_list);
  12. Button btn1 = findViewById(R.id.button1);
  13. btn1.setOnClickListener(new View.OnClickListener() {
  14. @Override
  15. public void onClick(View view) {
  16. Toast.makeText(LineList.this, "helloworld", Toast.LENGTH_SHORT).show();
  17. }
  18. });
  19. }
  20. }

基本的逻辑

  1. Button btn1 = findViewById(R.id.button1);
  2. btn1.setOnClickListener(new View.OnClickListener() {
  3. @Override
  4. public void onClick(View view) {
  5. Toast.makeText(LineList.this, "helloworld", Toast.LENGTH_SHORT).show();
  6. }
  7. });
  • findViewById 找到这个元素
  • 调用setOnClickListener 方法,传入一个View的OnclickListener实例,并重写了onClick方法

封装 View.OnClickListener

  1. package com.example.myapplication;
  2. import android.os.Bundle;
  3. import android.view.View;
  4. import android.widget.Button;
  5. import android.widget.Toast;
  6. import androidx.appcompat.app.AppCompatActivity;
  7. public class LineList extends AppCompatActivity {
  8. private Button btn1;
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_line_list);
  13. btn1 = findViewById(R.id.button1);
  14. OnClick onClick = new OnClick();
  15. btn1.setOnClickListener(onClick);
  16. }
  17. class OnClick implements View.OnClickListener {
  18. @Override
  19. public void onClick(View v) {
  20. switch (v.getId()) {
  21. case R.id.button1:
  22. Toast.makeText(LineList.this, "helloworld", Toast.LENGTH_SHORT).show();
  23. break;
  24. }
  25. }
  26. }
  27. }

重写好OnClickListener

  1. class OnClick implements View.OnClickListener {
  2. @Override
  3. public void onClick(View v) {
  4. switch (v.getId()) {
  5. case R.id.button1:
  6. Toast.makeText(LineList.this, "helloworld", Toast.LENGTH_SHORT).show();
  7. break;
  8. }
  9. }
  10. }

用setOnClickListener时直接传入这个写好的View.OnClickListener的实例

  1. OnClick onClick = new OnClick();
  2. btn1.setOnClickListener(onClick);