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

自訂帶參數的 Android Button:ParamButton 實作

編輯:關於 Android 程式設計

標準的 Button 無法直接攜帶自訂資料,當我們希望在按鈕上綁定額外的整數參數時,可以透過繼承 Button 來自訂一個子類別。以下是一個簡潔的實作範例:

public class ParamButton extends Button {
    private int mParam;
    public ParamButton(Context context) {
        super(context);
    }
    public ParamButton(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
    }
    void setIntParam(int p) {
        mParam = p;
    }
    int getIntParam() {
        return mParam;
    }
}

這個自訂控件在標準 Button 的基礎上額外維護了一個 mParam 成員變數,並透過 setIntParam() 與 getIntParam() 提供寫入與讀取的能力。如此一來,就能在每個按鈕上各自保存一份獨立的參數資料,非常適合需要為多個按鈕區分不同行為的情境。

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