對 XML 中的一個或多個檢視使用相同的單擊事件

當我們在佈局中建立任何 View 時,我們可以使用 android:onClick 屬性來引用相關活動或片段中的方法來處理 click 事件。

XML 佈局

<Button android:id="@+id/button"
    ...
    // onClick should reference the method in your activity or fragment
    android:onClick="doSomething" />

// Note that this works with any class which is a subclass of View, not just Button
<ImageView android:id="@+id/image"
    ...
    android:onClick="doSomething" />

活動/片段程式碼

在你的程式碼中,建立你命名的方法,其中 v 將是被觸控的檢視,併為呼叫此方法的每個檢視執行某些操作。

public void doSomething(View v) {
    switch(v.getId()) {
        case R.id.button:
            // Button was clicked, do something.
            break;
        case R.id.image:
            // Image was clicked, do something else.
            break;
    }
}

如果需要,你還可以為每個 View 使用不同的方法(在這種情況下,你當然不必檢查 ID)。