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

Android 中 RadioButton 的進階用法:讓文字靠右、圖示靠左

編輯:關於 Android 程式設計

常常有開發者問:在 Android 裡,能不能把 RadioButton 的文字放到右邊、圓形選取圖示放到左邊?預設的 RadioButton 是圖示在左、文字在右,若要做成相反的排版,其實只需要兩個屬性就能搞定。

解法:先隱藏,再重畫

第一步:透過 android:button="@null" 把系統原生的 RadioButton 圓形圖示隱藏起來。

第二步:透過 android:drawableRight="@android:drawable/btn_radio",在文字的右側放上一個系統內建的 btn_radio 圖示。可以想成 RadioButton 本身就是對 btn_radio 這個圖示的一層封裝。

以下是一個完整的版面配置範例:

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

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
           android:button="@null"
            android:checked="true"
            android:drawableRight="@android:drawable/btn_radio"
            android:paddingLeft="10dp"
            android:text="RadioButton" />

        <RadioButton
            android:id="@+id/button2"
            android:layout_width="319dp"
            android:layout_height="wrap_content"
            android:button="@null"
            android:drawableRight="@android:drawable/btn_radio"
            android:paddingLeft="10dp"
            android:text="RadioButton" />

    </RadioGroup>
</LinearLayout>

透過這樣的組合,就能實現「文字在左、選取圖示在右」的效果,同時仍完整保留 RadioGroup 的單選邏輯。若日後想改成圖示在左,只要把 drawableRight 換成 drawableLeft 即可。

參考網站:https://www.02521.com/cod/10496.html

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