1)第一種,也是最長見的添加方法(一下都以Button為例)- Button btn = (Button) findViewById(R.id.myButton);
- btn <span style="color: rgb(0, 0, 205);">.setOnClickListener(new View.OnClickListener() {</span>
- public void onClick(View v) {
- //do something
- }
- });
複製代碼 2)第二種,下面這個方法較前一種稍微簡單了一些,允許多個Buttons共享一個Listener。通過Switch控制對不同Button Click事件的響應方法:- Button btn = (Button) findViewById(R.id.mybutton);
- Button btn2 = (Button) findViewById(R.id.mybutton2);
- <span style="color: rgb(0, 0, 255);">btn.setOnClickListener(handler);</span>
- btn2.setOnClickListener(handler);
- View.OnClickListener handler = View.OnClickListener() {
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.mybutton:
- //do something
- break;
- case R.id.mybutton2:
- //do something
- break;
- }
- }
複製代碼 3)第三種,直接將Clicklistener捆綁XML layout中的Views元素,在程序中定義的Listener方法需要帶有一個View類型的參數:- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView android:layout_width="fill_parent"
- android:layout_height="wrap_content" android:id="@+id/text"
- android:text="@string/hello" />
- <Button android:id="@+id/mybutton" android:layout_height="wrap_content"
- android:layout_width="wrap_content" <span style="color: rgb(0, 0, 255);">android:onClick="mybuttonlistener"</span>></Button>
- </LinearLayout>
複製代碼- Button btn = (Button) findViewById(R.id.mybutton);
-
- public void mybuttonlistener(View target){
- //do something
- }
複製代碼 |