public void (View v) 記得函數參數匹配 根據多態性以及函數指針原理這裏的函數會註冊給android:onClick的監聽器java
這樣每一個button均可以使用onClck定義本身測處理方法,也能夠共用,可是關於事件源的區分就沒有那麼方便了,可能須要獲取座標才能邏輯上判斷是哪一個按鈕或者根據android
完整例子web
main.xmlapp
<?xml version="1.0"encoding="utf-8"?>ide
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"函數
android:orientation="vertical"this
android:layout_width="fill_parent"spa
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>
<Button
android:onClick = "xxx"
android:text="no" android:id="@+id/button2" android:layout_width="wrap_content"android:layout_height="wrap_content"></Button>
</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();
}
}