需實現:RadioButton 選中/未選中時,**drawableTop 圖片**與**文字顏色**同時變化。XML 中使用 android:button="@null" 隱藏默認圓點,配合 android:drawableTop 設置圖標,但發現 Selector 作用於 background 時圖片顯示在底層,無法實現 drawableTop 的狀態切換。
RadioButton rb = findViewById(R.id.my_radio_button);
rb.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
rb.setCompoundDrawablesWithIntrinsicBounds(
0, R.drawable.icon_selected, 0, 0); // drawableTop
rb.setTextColor(ContextCompat.getColor(this, R.color.colorSelected));
} else {
rb.setCompoundDrawablesWithIntrinsicBounds(
0, R.drawable.icon_normal, 0, 0);
rb.setTextColor(ContextCompat.getColor(this, R.color.colorNormal));
}
});
優點: 邏輯清晰,支持複雜狀態(如不可用態),無需繁瑣 XML Selector。
res/drawable/rb_icon_selector.xml:
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/icon_selected" />
<item android:drawable="@drawable/icon_normal" />
</selector>
佈局中:
<RadioButton
android:id="@+id/rb_tab"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:drawableTop="@drawable/rb_icon_selector" <!-- 直接引用 Selector -->
android:text="Tab1"
android:textColor="@drawable/rb_text_color_selector" <!-- 文字顏色也用 Selector -->
android:gravity="center"
android:background="@drawable/rb_bg_selector" />
注意: drawableTop 支持 Selector 狀態響應需要 **API 23 (Android 6.0) 以上**。低版本需用方案一或自定義 View 重寫 onDraw/drawableStateChanged。
public class StatefulIconRadioButton extends RadioButton {
public StatefulIconRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
// 根據 isChecked() 動態設置 drawableTop、textColor
updateDrawableAndText();
}
private void updateDrawableAndText() { /* 同方案一邏輯 */ }
}
佈局中直接使用 <com.yourpkg.StatefulIconRadioButton ... />,實現 XML 聲明式使用、邏輯內聚。
ColorStateList (XML Selector) 或代碼 setTextColor(ColorStateList) 實現狀態變色,單純 android:textColor 僅接受單一顏色值。