Android Button的几种监听方式
1、一个Button对应一个监听
1)xml文件中绑定监听
<Buttonandroid:id="@+id/btn_test"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="test listener"android:onClick="test"/>
在对应文件中实现该方法
public void test(View v){// to do somethingToast.makeText(this, "xml绑定监听响应", Toast.LENGTH_SHORT).show(); }
2)
Button btnTest = (Button) findViewById(R.id.btn_test); btnTest.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub } });
2、多个Button对应一个监听
1)
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btnTest = (Button) findViewById(R.id.btn_test);Button btnDeploy = (Button) findViewById(R.id.btn_deploy);btnTest.setOnClickListener(listener);btnDeploy.setOnClickListener(listener);}OnClickListener listener = new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.btn_test:break;case R.id.btn_deploy:break;default:break;}}}; }
2)
public class MainActivity extends Activity implements OnClickListener{@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btnTest = (Button) findViewById(R.id.btn_test);Button btnDeploy = (Button) findViewById(R.id.btn_deploy);btnTest.setOnClickListener(this);btnDeploy.setOnClickListener(this);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.btn_test:break;case R.id.btn_deploy:break;default:break;}} }