自定义CheckBox和RadioButton

1 drawable-mdpi文件夹下创建文件checkbox_selector.xml

 

<?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/login_checked" /><!--选中时效果-->

<item android:state_checked="false"

android:drawable="@drawable/login_unchecked" /><!--未选中时效果-->

</selector>

 

2 values文件夹下创建styles.xml

 

<?xml version="1.0" encoding="utf-8"?>

<resources>

 

<style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">

 

<!-- 将原来系统的CheckBox图标隐藏起来。 -->

<item name="android:button">@null</item>

 

<!-- 设置CheckBox的左间距 -->

<item name="android:paddingLeft">10dip</item>

 

<!-- 设置CheckBox的最大高度 -->

<item name="android:maxHeight">50.0dip</item>

 

<!-- 设置文字和图标的间距 -->

<item name="android:drawablePadding">50dp</item>

 

<!-- 在CheckBox的右侧添加自定义的图标 -->

<item name="android:drawableRight">@drawable/checkbox_selector</item>

 

</style>

 

</resources>

 

3 xml文件的CheckBox中添加属性

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

 

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="自定义CheckBox和RadioButton"

android:gravity="center_horizontal"

android:paddingBottom="50dp"/>

 

<CheckBox

android:id="@+id/check_box"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

style="@style/MyCheckBox" <!-- 引用自定义样式 -->

android:text="good boy"

android:textSize="20sp"

android:textScaleX="1.0" <!-- 设置文字间距 -->

/>

 

<RadioGroup

android:id="@+id/radioGroup1"

android:layout_width="match_parent"

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="400dp"

android:layout_height="wrap_content"

android:button="@null"

android:drawableRight="@android:drawable/btn_radio"

android:paddingLeft="10dp"

android:text="RadioButton" />

 

</RadioGroup>

 

</LinearLayout>

 

最后效果如下图:


 

注意:CheckBox图标的大小只由被援引图片的本身大小决定,无法在java程序的xml中进行设定。所以为适应多种尺寸和密度的屏幕,应创建drawable-normal-mdpidrawable-normal-hdpidrawable-large-xhdpi和相应values-normal-mdpivalues-normal-hdpivalues-large-xhdpi等多个资源文件夹并放入相应的资源文件和图片,如下图所示:

 


猜你喜欢

转载自wait7758521.iteye.com/blog/1695376