Android四种监听方式:
- 实现监听的接口
- 实现匿名内部类
- 使用外部类
- 直接在xml中设置监听
1、使用接口方式实现监听事件:
可直接在Activity中定义事件处理方法
优点:简洁
缺点:可能造成程序结构混乱
2、实现匿名内部类实现监听:
优点:可以在当前类中复用该监听器,可自由访问外部类的所有界面组件
3、使用外部类实现监听:
优点:当某事件监听器被多个GUI界面共享,且只要是完成某种业务逻辑的实现
缺点:不利于提供程序内聚性,不能自由访问创建GUI界面类的组件,界面不够简洁
4、直接在xml文件中设置监听:
在需要监听的控件中添加:Android:conClick="xxx"
再在布局对应的Activity中定义public void xxx(View view){}
测试程序:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/button1"
android:text="接口方式设置监听器"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button2"
android:text="直接在xml文件中绑定"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="button2OnClick"/>
<Button
android:id="@+id/button3"
android:text="使用匿名内部类设置监听器"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button4"
android:text="使用外部类设置监听器"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity:
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Context context = MainActivity.this;
private Button button1;
private Button button2;
private Button button3;
private Button button4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button1.setOnClickListener(this);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context,"使用匿名内部类实现监听", Toast.LENGTH_SHORT).show();
}
});
button4.setOnClickListener(new MyOnClickListener() {
public void onClick(View view){
super.onClick(view);
}
});
}
public void button2OnClick(View view){
Toast.makeText(context,"直接在xml文件中绑定", Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Toast.makeText(context,"以接口的方式设置监听器", Toast.LENGTH_SHORT).show();
break;
}
}
class MyOnClickListener implements View.OnClickListener{
@Override
public void onClick(View view) {
Toast.makeText(context,"使用外部类设置监听器", Toast.LENGTH_SHORT).show();
}
}
}