---
title: "View 的 setOnClickListener"
author: "canfly2010"
date: "2012-11-22T14:50:37Z"
tags: []
categories: ["移动开发"]
slug: "view-setonclicklistener"
draft: false
lastmod: "2012-11-22T14:50:37Z"
id: 1733296
url: "https://canfly2010.iteye.com/blog/1733296"
---

View的setOnClickListener的添加方法  
1）第一种，也是最长见的添加方法（一下都以Button为例）

Button btn = (Button) findViewById(R.id.myButton);  
btn .setOnClickListener(new View.OnClickListener() {  
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);  
btn.setOnClickListener(handler);  
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类型的参数：

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;LinearLayout xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
android:orientation="vertical" android:layout\_width="fill\_parent"  
android:layout\_height="fill\_parent"&gt;  
&lt;TextView android:layout\_width="fill\_parent"  
android:layout\_height="wrap\_content" android:id="@+id/text"  
android:text="@string/hello" /&gt;  
&lt;Button android:id="@+id/mybutton" android:layout\_height="wrap\_content"  
android:layout\_width="wrap\_content" android:onClick="mybuttonlistener"&gt;&lt;/Button&gt;  
&lt;/LinearLayout&gt;

java代码：

Button btn = (Button) findViewById(R.id.mybutton);  
public void mybuttonlistener(View target){  
//do something  
}