Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 按鈕點擊的三種回應寫法對照

編輯:關於 Android 程式設計

點擊事件是 Android 開發最基礎的互動,而實作方式其實有三種。以下逐一對照說明。

方法一:在版面檔中直接指定方法名稱

activity_main.xml:

 <Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/show_toast"
 android:onClick="showToast" >
 </Button>

MainActivity.java 中只要補上對應的 public 方法即可,注意方法簽名必須接收一個 View 參數:

 /**
 * 顯示 toast 提示訊息
 * @param v
 */
 public void showToast(View v) {
 Toast.makeText(MainActivity.this, "這裡是提示訊息", Toast.LENGTH_SHORT).show();
 }

這種寫法的好處是直覺,缺點是方法名稱寫在 XML 裡,若後端方法改名而忘記同步,編譯階段不會報錯,卻會在執行時才炸掉。

方法二:匿名內部類別監聽器

activity_main.xml:

 <Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/changeToRed"
 android:id="@+id/button2" >
 </Button>
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 Button button2 = (Button) findViewById(R.id.button2);
 button2.setOnClickListener(new OnClickListener() {
 public void onClick(View v) {
 text.setBackgroundColor(Color.RED);
 }
 });
 }

這是最常見的寫法,每個控制項各自獨立,可讀性高。

方法三:讓 Activity 自己實作監聽介面

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.testevent);

 mText = (TextView) findViewById(R.id.text1);

 mButton1 = (Button) findViewById(R.id.button1);
 mButton1.setOnClickListener(this);

 mButton2 = (Button) findViewById(R.id.button2);
 mButton2.setOnClickListener(this);
 }

 public void onClick(View v) {
 Log.v(TAG, "onClick()");
 switch (v.getId()) {
 case R.id.button1:
 mText.setBackgroundColor(Color.RED);
 break;
 case R.id.button2:
 mText.setBackgroundColor(Color.GREEN);
 break;
 default:
 Log.v(TAG, "other");
 break;
 }
 }

當畫面上有大量按鈕時,這種集中式寫法能避免產生一堆匿名類別;代價是 onClick 內部要自己用 switch 分流,按鈕一多可讀性就會下降。

三種方式沒有絕對優劣:按鈕少而邏輯各自獨立時,方法二最清晰;按鈕數量龐大且行為相似時,方法三比較精簡;方法一則適合極簡單的展示型頁面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved