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

Android Button 點擊事件的三種實作方式與選擇建議

編輯:關於 Android 程式設計

Button 大概是最簡單的控件,卻也是使用頻率最高的。設定點擊事件有三種常見寫法,各有適用的場合,本文逐一說明並給出完整可執行的範例。

做法一:匿名內部類

最直觀的寫法,適合「只會用到一次」或邏輯很短的按鈕:

button1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        System.out.println("您點擊了 Button1");
    }
});

程式碼短、意圖清楚,但如果每顆按鈕都這樣寫,Activity 會被大量匿名類塞滿,可讀性反而下降。

做法二:實作 OnClickListener 介面

當畫面上有多顆按鈕,或同一組事件要重複使用時,讓 Activity 自己實作介面,再用 switch(v.getId()) 分派:

public class MainActivity extends Activity implements OnClickListener {

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button2:
                System.out.println("您點擊了 Button2");
                break;
            default:
                break;
        }
    }
}

因為實作了介面,就必須實作其中的方法,編譯器會幫你檢查。這種寫法的好處是事件集中、易於維護;缺點是 Activity 職責變重,按鈕一多 switch 就開始膨脹。

做法三:在版面檔宣告 android:onClick

最省事的寫法,直接在 XML 上指定方法名:

<Button
    android:id="@+id/button3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button3 測試"
    android:onClick="clickHandler" />

然後在 Activity 中寫出對應的方法,方法簽名必須是 public void 且只接受一個 View 參數,否則會在點擊時丟 IllegalStateException:

public void clickHandler(View view) {
    System.out.println("您點擊了 Button3");
}

這個做法的缺點是介面與邏輯耦合在 XML 上,重構時容易漏改;而且一旦使用 Fragment,事件會被 &-gt; Activity 攔截,方法必須放在 Activity 而非 Fragment 中,容易造成誤解。

完整範例:版面檔

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button1 測試" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button2 測試" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button3 測試"
        android:onClick="clickHandler" />
</LinearLayout>

執行結果如下圖:

完整範例:Activity

package com.example.buttonclicktest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    private Button button1 = null;
    private Button button2 = null;

    public void findButton() {
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findButton();
        button2.setOnClickListener(this);   // 做法二:共用同一個監聽器

        // 做法一:匿名內部類
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                System.out.println("您點擊了 Button1");
            }
        });
        // 做法三由 XML 的 android:onClick 負責,不需在此設定
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button2:
                System.out.println("您點擊了 Button2");
                break;
            default:
                break;
        }
    }

    /** 對應 XML 中的 android:onClick="clickHandler" */
    public void clickHandler(View view) {
        System.out.println("您點擊了 Button3");
    }
}

點下去之後,Logcat 會印出對應訊息:

該怎麼選

只有一顆按鈕、邏輯兩三行,用匿名內部類最俐落。同一頁有多顆按鈕且行為相近(例如表單的送出、清除、返回),用實作介面加 switch 最容易一眼看懂。若只是幾個各自獨立、邏輯互不相關的按鈕,各自掛匿名內部類反而比塞進一個巨大的 switch 清楚。

補充兩點實務建議:Kotlin 可以直接寫 button.setOnClickListener { ... },比 Java 的匿名類精簡得多;而在重構或元件數量較多的畫面上,改用 ViewBinding 取代 findViewById() 能省下大量樣板程式碼,也避免 id 打錯造成的空指標。至於 XML 的 android:onClick,除非是很簡單的 demo,否則不建議在正式專案中使用。

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