您的位置:首页 > 移动开发 > Android开发

CheckBox选择框和文字设置间距

2015-08-31 16:50 495 查看
由于界面美观度的需求,需要自定义CheckBox的选择框。

传统的方法是先定义一个CheckBox的自定义style,如下:

</pre><pre name="code" class="html"> <span style="font-size:14px;"><style name="CustomCheckboxTheme" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:button">@drawable/checkbox_selector</item>
</style></span>

style中使用的checkbox_selector.xml

<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checkbox_unselected" android:state_selected="false"/>
<item android:drawable="@drawable/checkbox_selected" android:state_selected="true"/>
<item android:drawable="@drawable/checkbox_unselected"/>
</selector></span>


最后在布局文件中使用style属性加上效果,就基本实现了自定义的选择框。

<CheckBox
android:textSize="17.0sp"
android:id="@+id/custom_checkbox"
android:text="测试"
android:layout_weight="1"
style="@style/CustomCheckboxTheme"/>
但是,以上实现的效果有个问题:checkbox自带的文字和选择框紧紧靠在一起,往往有时候界面需求是要一定的间隔的。

解决方法如下:

<CheckBox
android:id="@+id/hasHouse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:background="@null"
android:button="@null"
android:clickable="true"
android:drawableLeft="@drawable/checkbox_selector"
android:drawablePadding="8dp"
android:text="测试"
android:textColor="@color/register_input"
android:textSize="16sp" />
大概的思路是运用checkbox的drawableLeft和drawablepadding两个属性搭配实现效果,当然,这里的button和background属性得注意隐藏。

以上方法对于radiobutton同样有效。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息