預設 RadioButton 圖標在左、文字在右。需求:將按鈕與文字整體靠右對齊,或實現「文字在左、圖標在右」的 RTL 效果。
在父容器 RadioGroup 或 RadioButton 上設定:
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="end"> <!-- 關鍵:子元素靠右 -->
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/task_name_1"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
</RadioGroup>
android:gravity="end"(API 17+)支援 RTL 自動適配paddingStart/End 替代 Left/Right<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/task_name_1"
android:button="@null" <!-- 隱藏預設圖標 -->
android:drawableEnd="@drawable/rb_selector" <!-- 文字右側放自定義圖標 -->
android:drawablePadding="8dp"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
rb_selector.xml 定義選中/未選中狀態圖片。
RadioButton rb = findViewById(R.id.rb);
rb.setGravity(Gravity.END); // 或 Gravity.RIGHT
// API 17+ 針對 RTL
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
rb.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_END);
}
<!-- res/drawable/rb_selector.xml -->
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/rb_checked" />
<item android:state_checked="false" android:drawable="@drawable/rb_unchecked" />
</selector>
layout_marginLeft 硬編碼:不同螢幕密度下位置會偏移start/end、gravity="end"、layoutDirection="rtl"minHeight="48dp" 符合 Material Design 觸控標準