使用 android:button="@drawable/custom_radio" 替換默認單選圖標後,文字與圖標間距靠 paddingLeft 硬編碼,導致不同密度屏幕 (mdpi/hdpi/xhdpi/xxhdpi/xxxhdpi) 顯示錯位:圖標過大文字重疊、或間距過大。
RadioButton 繼承 CompoundButton,其 buttonDrawable 繪製在文本左側 (或 android:gravity 指定側)。文本起始位置由 paddingLeft 決定,**需動態等於圖標固有寬度 + 期望間距**。
RadioButton rb = findViewById(R.id.radio_button); rb.setButtonDrawable(R.drawable.custom_radio); // 設置自定義圖標 // 獲取圖標固有寬度 (px) Drawable drawable = getResources().getDrawable(R.drawable.custom_radio); int iconWidth = drawable.getIntrinsicWidth(); // 包含 9-patch 邊距 // 動態設置 paddingLeft = 圖標寬度 + 期望間距 (如 8dp) int gapPx = (int) (8 * getResources().getDisplayMetrics().density); rb.setPadding(iconWidth + gapPx, rb.getPaddingTop(), rb.getPaddingRight(), rb.getPaddingBottom());
fun RadioButton.setupCustomButton(@DrawableRes int drawableRes, @DimenRes int gapRes) {
setButtonDrawable(drawableRes)
val drawable = ContextCompat.getDrawable(context, drawableRes)!!
val gapPx = resources.getDimensionPixelSize(gapRes)
setPaddingRelative(drawable.intrinsicWidth + gapPx, paddingTop, paddingEnd, paddingBottom)
}
// 使用
radioButton.setupCustomButton(R.drawable.custom_radio, R.dimen.radio_gap)
<RadioButton
android:id="@+id/rb_option"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="選項文字"
android:button="@null" <!-- 重要:XML 不預設 button,由代碼動態設置 -->
android:paddingTop="12dp"
android:paddingBottom="12dp"
android:gravity="center_vertical" />
// 使用 setPaddingRelative (API 17+) 自動適配 RTL // LTR: paddingStart = iconWidth + gap // RTL: paddingEnd = iconWidth + gap rb.setPaddingRelative(iconWidth + gapPx, rb.getPaddingTop(), rb.getPaddingEnd(), rb.getPaddingBottom());
getIntrinsicWidth() 返回內容區域寬度,計算更精準New → Drawable resource file → 勾選 9-patch 或 Draw 9-patch 工具<LinearLayout android:orientation="horizontal" android:gravity="center_vertical" ...>
<ImageView
android:id="@+id/iv_radio"
android:layout_width="24dp"
android:layout_height="24dp"
android:src="@drawable/custom_radio" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="選項文字" />
</LinearLayout>
優點:完全控制圖標大小、間距、對齊、動畫;缺點:需自行管理選中狀態 (可用 StateListDrawable 或 RadioGroup 邏輯控制)。
RadioButton 自定義圖標時,**動態計算 paddingStart = icon.intrinsicWidth + gap** 是最輕量、兼容性最好的方案。配合 .9.png 圖標與 setPaddingRelative 可完美適配多密度、RTL、字體縮放等場景。複雜佈局建議拆分為 ImageView + TextView 組合,獲得最大靈活度。