android 四种监听方式
- 实现监听的接口
- 实现匿名内部类
- 在xml 上设置 监听(不建议采用)
- 内部类的形式
-
经常采用的形式 (实际开发中经常用到的,建议采用)
public class MainActivity extends Activity implements OnClickListener {
private Button mBut1, mBut2, mBut3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void initView() {
mBut1 = (Button) findViewById(R.id.But1);
mBut2 = (Button) findViewById(R.id.But2);
mBut3= (Button) findViewById(R.id.But3);
mBut1.setOnClickListener(this);
mBut2.setOnClickListener(this);
mBut3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int ID = v.getId();
if (R.id.But1 == ID) {
Log.e("main", "点击按钮一");
} else if (R.id.But2 == ID) {
Log.e("main", "点击按钮二");
} else if(R.id.But3==ID){
Log.e("main", "点击按钮三");
}
}
}
采用匿名内部类和其他两种的形式
public class MainActivity extends Activity {
private Button mBtn1;
private Button mBtn2;
private MyOnclick onclick = new MyOnclick();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
mBtn1 = (Button) findViewById(R.id.Btn1);
mBtn2 = (Button) findViewById(R.id.Btn2);
mBtn2.setOnClickListener(onclick);
mBtn1.setText("按钮");
mBtn1.setBackgroundResource(R.drawable.ic_launcher);
Log.e("Main", "initview设置监听前");
mBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("Main", "initview监听执行中");
}
});
Log.e("Main", "initview设置监听后");
}
public void MyOn(View v){
Log.e("Main","XML监听");
}
private class MyOnclick implements View.OnClickListener{
@Override
public void onClick(View v) {
Log.e("Main","内部类监听执行");
}
}
}