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

Android 簡明開發教程十六:把 RadioButton 換成 Button 的畫刷切換

編輯:Android 開發教學

這個範例是上一個的變體:把原本用來切換的 RadioButton 換成 Button,其餘結構大致相同。

在 res/layout 中新增 brush.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@drawable/white"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.pstreets.graphics2d.GuidebeeGraphics2DView
        android:id="@+id/graphics2dview"
        android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button android:text="Pattern"
            android:id="@+id/btnPattern"
            android:layout_width="wrap_content"
            android:textColor="@color/black"
            android:checked="true"
            android:layout_height="wrap_content">
        </Button>

        <Button android:text="Gradients"
            android:id="@+id/btnGradients"
            android:layout_width="wrap_content"
            android:textColor="@color/black"
            android:layout_height="wrap_content">
        </Button>

    </LinearLayout>
</LinearLayout>

换掉控件的意義在哪

表面上看這只是把 RadioButton 替換成 Button,但背後反映的是一個介面設計上的取捨。

RadioButton 放在 RadioGroup 裡,天生就是「單選」語意——使用者一眼就知道這些選項互斥,而且框架會幫你保證同一時間只有一個被選中。

Button 則沒有這層語意。它預設是「按一下就觸發一個動作」,要拿來當切換鈕用,你必須自己維護「目前哪個作用中」的狀態,並手動更新每個按鈕的外觀。

所以這個範例真正在教你的是:當你選擇用 Button 實作切換時,額外的狀態管理責任就落在你身上。

實作上的建議

如果你的目標只是視覺風格,其實有更省事的做法:保留 RadioButton 的單選邏輯,改用 style 或自訂 selector 換掉外觀,就能同時拿到「框架保證互斥」與「想要的樣子」。

若堅持用 Button,建議做兩件事:一是用 toggleButton 或自行以 background 的 selector 反映選中狀態,讓使用者有視覺回饋;二是把「切換」這件事集中到一個方法裡處理,避免在每個 setOnClickListener 中重複寫更新邏輯。

另外,這裡的 android:checked="true" 放在 Button 上其實不會有實際效果,因為 Button 並沒有 checked 屬性——這也是從 RadioButton 改寫過來時容易殘留的痕跡,值得留意。

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