View的setOnClickListener的添加方法

1)第一种,也是最长见的添加方法(一下都以Button为例)

复制代码
1 Button btn = (Button) findViewById(R.id.myButton);
2 btn .setOnClickListener(new View.OnClickListener() {
3         public void onClick(View v) {
4 //do something5         }
6     });
复制代码

 

2)第二种,下面这个方法较前一种稍微简单了一些,允许多个Buttons共享一个Listener。通过Switch控制对不同Button Click事件的响应方法:

复制代码
 1 Button btn = (Button) findViewById(R.id.mybutton);  2 Button btn2 = (Button) findViewById(R.id.mybutton2);  3 btn.setOnClickListener(handler);  4 btn2.setOnClickListener(handler);  5 View.OnClickListener handler = View.OnClickListener() {  6         public void onClick(View v) {  7             switch (v.getId()) {  8                case R.id.mybutton:   9 //do something10                break; 11                case R.id.mybutton2:  12 //do something13                break; 14             } 15     }
复制代码

3)第三种,直接将Clicklistener捆绑XML layout中的Views元素,在程序中定义的Listener方法需要带有一个View类型的参数:

复制代码
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     android:orientation="vertical" android:layout_width="fill_parent" 4     android:layout_height="fill_parent">
 5     <TextView android:layout_width="fill_parent" 6         android:layout_height="wrap_content" android:id="@+id/text" 7         android:text="@string/hello"/>
 8     <Button android:id="@+id/mybutton" android:layout_height="wrap_content" 9         android:layout_width="wrap_content" android:onClick="mybuttonlistener"></Button>
10 </LinearLayout>
复制代码

java代码:

复制代码
1 Button btn = (Button) findViewById(R.id.mybutton); 2  3 public void mybuttonlistener(View target){ 4 //do something5     }
原文地址:https://www.cnblogs.com/LiaoHao/p/3256927.html