public void (View v) 记得函数参数匹配 根据多态性以及函数指针原理这里的函数会注册给android:onClick的监听器
这样每个button都可以使用onClck定义自己测处理方法,也可以共用,但是关于事件源的区分就没有那么方便了,可能需要获取坐标才能逻辑上判断是哪个按钮或者根据

完整例子

main.xml

<?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:text="@string/hello"/><Button    android:onClick = "xxx"    android:text="ok"     android:id="@+id/button1"     android:layout_width="wrap_content"    android:layout_height="wrap_content"/><Button   android:onClick = "xxx"   android:text="no"    android:id="@+id/button2"    android:layout_width="wrap_content"   android:layout_height="wrap_content"/></LinearLayout>


MainActivity.java

package com.sms; import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainAcitivy extends Activity {   /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       setContentView(R.layout.main);    }    public void xxx(View v){       //可以直接转型但是注意有时候子类不匹配  ((Button)v).getText()       Button temp = (Button)v;   //最好用instanceof判断子类型的实例,,注意子类型和子类不一样,面向对象设计原理       if(temp.getText().toString().trim().equalsIgnoreCase("ok")){           Toast.makeText(this,"ok ", Toast.LENGTH_SHORT).show();       }       if(temp.getText().toString().trim().equalsIgnoreCase("no")){           Toast.makeText(this,"no ", Toast.LENGTH_LONG).show();       }   }   public void xxxx(View v){ //也可以单独映射自己的方法,但是单独写代码过于冗余 所以建议统一 使用getText判断仍然是好方法,需要记住处理函数参数       Toast.makeText(this,"xxxx", Toast.LENGTH_SHORT).show();  }}

更多相关文章

  1. android常用控件一二
  2. 利用Xposed Hook打印Java函数调用堆栈信息的几种方法
  3. Android(安卓)中使用 Proguard 混淆 Java 代码
  4. Android(安卓)JNI开发进阶篇
  5. webrtc之Android视频质量提升:保帧率降分辨率
  6. 【Android开发学习35】GL_TRIANGLE_STRIP之纹理贴图
  7. Kotlin For Android介绍
  8. Android判断当前界面是否是桌面(主页)
  9. Android-SQLite使用总结

随机推荐

  1. android利用jdk制作签名
  2. Android恢复出厂设置流程分析
  3. Android(安卓)surfaceview 自定义相机 拍
  4. Android底部fragment互相跳转
  5. Android录音--AudioRecord、MediaRecorde
  6. 小白用网格布局实现简单的计算器 ——And
  7. Android(安卓)Studio配置百度地图开发环
  8. Ubuntu编译ijkplayer支持https和更多视频
  9. Android(安卓)注解
  10. cocos2d-x android 添加新场景报错: unde