Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Button 控件用法詳解:從繼承體系到兩種綁定方式

編輯:Android 開發實例

Button 大概是 Android 里最基礎的交互控件,但也正因為基礎,很多人只會用 setOnClickListener 一種寫法。本文把它的家族關係、兩種事件綁定方式和常用屬性整理清楚。

一、Button 在繼承鏈上的位置

android.widget.Button 直接繼承自 android.widget.TextView,這也解釋了為什麼它天生支持 text、textColor、textSize 這一整套文本屬性。

它的直接子類是 CompoundButton;而 CheckBox、RadioButton、Switch、ToggleButton 則是通過 CompoundButton 間接派生而來,這些控件都帶有「選中/未選中」的雙態語義。

作為控件本身,Button 的作用很單純:用戶按下或點擊它,觸發一段操作。

二、用法一:在代碼中綁定監聽

這是最直白的寫法,在 onCreate 裡拿到控件實例後綁定 OnClickListener:

 public class MyActivity extends Activity {
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.content_layout_id);
        final Button button = (Button) findViewById(R.id.button_id);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 在這裡處理點擊邏輯
            }
        });
    }
}

三、用法二:在 XML 中綁定

如果不想寫匿名內部類,可以直接在布局裡用 android:onClick 指定方法名:

 <Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/self_destruct"
    android:onClick="selfDestruct" />

此時用戶點擊按鈕,系統會去 Activity 中查找同名方法並調用。這個方法有兩個硬性要求:必須是 public,且只接受一個 View 類型參數。被點擊的控件會作為參數傳入:

 public void selfDestruct(View view) {
    // 執行相應操作
}

這種寫法的好處是代碼更精簡,缺點是方法名寫死在布局裡,重構時容易被遺漏,而且一旦 Activity 中找不到對應方法或簽名不符,會在運行時直接崩潰。

四、XML 屬性與常用方法

Button 的 XML 屬性和 public 方法基本沿用自 TextView,諸如 android:text、android:textColor、android:textSize、android:background、android:drawableLeft 等都可以直接使用;代碼側則常用 setText()、setEnabled()、setClickable() 等。有興趣的讀者可以對照 TextView 的文檔一起看,內容幾乎一致。

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