A:线性垂直布局页面`
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点击事件的几种方法" />
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第一种" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第二种" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第三种" />
<Button
android:onClick="click"
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第四种" />
<Button
android:onClick="click"
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第五种" />
</LinearLayout>
B:逻辑部分
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
/**
* 一定的要带 view 这个参数
*
* 保持这种格式
*
* @param view
*/
public void click(View view) {
// 单个事件 不需要switch
// 多个设置onclick 是一样的 即 同名函数 加上 id 区分
switch (view.getId()) {
case R.id.btn4:
System.out.println("第四种 采用onclick点击事件");
Log.d("qishui", "第四种 采用onclick点击事件");
break;
case R.id.btn5:
System.out.println("第五种 采用onclick点击事件");
Log.d("qishui", "第五种 采用onclick点击事件");
break;
default:
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 第一种 使用匿名内部类
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("第一种 使用匿名内部类");
Log.d("qishui", "第一种 使用匿名内部类");
}
});
// 第二种 使用匿名内部类
Button btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new MyClick());
// 第三种 实现OnClickListener接口
Button btn3 = (Button) findViewById(R.id.btn3);
btn3.setOnClickListener(this);
}
/**
* 实现OnClickListener接口
*
* @author zhouwenxi
*
*/
class MyClick implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("第二种 自定义MyClick使用实现OnClickListener接口");
Log.d("qishui", "第二种 自定义MyClick使用实现OnClickListener接口");
}
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.btn3:
System.out.println("第三种 MainActivity使用实现类");
Log.d("qishui", "第三种 MainActivity使用实现类");
break;
default:
break;
}
}
}
C:效果截图
D:源码下载链接