第一种通常在activity组件的oncreate事件中直接定义,直接动作。
这样的方式每一个控件都定义一次。通常不方便.
Button btn = (Button) findViewById(R.id.myButton);
btn .setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do something
}
});
另外一种一般是在activity组件实现其接口。这样能够多外控件共享一个接口,这样相对方便
public class TestMedia extends Activity implements View.OnClickListener{
Button btn1 = (Button) findViewById(R.id.myButton1);
Button btn2 = (Button) findViewById(R.id.myButton2);
btn1 .setOnClickListener();
btn2 .setOnClickListener();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id. myButton1:
//do something
break;
case R.id. myButton2:
//do something
break;
}
第三种类似另外一种,这种优点在于假设须要实现多个监听接口,这样更清晰
public class TestMedia extends Activity {
Button btn1 = (Button) findViewById(R.id.myButton1);
Button btn2 = (Button) findViewById(R.id.myButton2);
btn1 .setOnClickListener(new ClickEvent());
btn2 .setOnClickListener(new ClickEvent());
}
class ClickEvent implements View.OnClickListener
public void onClick(View v) {
switch (v.getId()) {
case R.id. myButton1:
//do something
break;
case R.id. myButton2:
//do something
break;
}