android CheckBox RadioButton 圖片與文字間距問題,
在使用自訂的CheckBox 或RadioButton時,自訂的表徵圖和文字在不同的手機上顯示的間距不同,有時不太好控制,下面是我自訂的CheckBox:
在Layout下的xml:
<CheckBox android:id="@+id/recharge_activity_cb" style="@style/CustomCheckboxTheme" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我已經閱讀並同意" android:textColor="@color/huoqiuLightblackColor" android:checked="true" />
裡面自訂的style,style內容為:
<!-- 自訂CheckBox --> <style name="CustomCheckboxTheme" parent="@android:style/Widget.CompoundButton.CheckBox"> <item name="android:button">@drawable/checkbox_style</item> <item name="android:paddingLeft">@dimen/dp8</item> </style>
其中調用了選中和未選中圖片,在drawable下:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_checked="true" android:drawable="@drawable/agree"/> <item android:state_checked="false" android:drawable="@drawable/disagree"/> <item android:drawable="@drawable/disagree"/></selector>
雖然通過設定paddingLeft在有的系統上可以顯示想要的,但是有些則不行
<item name="android:paddingLeft">@dimen/dp8</item>
那麼問題來了,到底用什麼方法可以解決呐?
下面是我的解決方案:使用CheckedTextView控制項
<CheckedTextView android:id="@+id/recharge_activity_ctv" android:checkMark="@drawable/checkbox_style" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" />
<TextView android:id="@+id/buy_write_jine_agree_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我已經閱讀並同意" android:textColor="@color/huoqiuLightblackColor" android:layout_marginLeft="@dimen/dp3" />
其中checkMark就是上面drawable下的那個選中狀態xml
android:checkMark="@drawable/checkbox_style"
然後在代碼中對CheckedTextView使用isChecked()判斷是否選中,使用toggle()方法設定選中和未選中效果,這樣就不存在表徵圖和文本的空隙問題了,問題完美解決!