基本的事件监听方式
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class LineList extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_line_list);
Button btn1 = findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(LineList.this, "helloworld", Toast.LENGTH_SHORT).show();
}
});
}
}
基本的逻辑
Button btn1 = findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(LineList.this, "helloworld", Toast.LENGTH_SHORT).show();
}
});
- findViewById 找到这个元素
- 调用setOnClickListener 方法,传入一个View的OnclickListener实例,并重写了onClick方法
封装 View.OnClickListener
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class LineList extends AppCompatActivity {
private Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_line_list);
btn1 = findViewById(R.id.button1);
OnClick onClick = new OnClick();
btn1.setOnClickListener(onClick);
}
class OnClick implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Toast.makeText(LineList.this, "helloworld", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
重写好OnClickListener
class OnClick implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Toast.makeText(LineList.this, "helloworld", Toast.LENGTH_SHORT).show();
break;
}
}
}
用setOnClickListener时直接传入这个写好的View.OnClickListener的实例
OnClick onClick = new OnClick();
btn1.setOnClickListener(onClick);