应项目需求需要做下面的带数字的按钮,选中的时候背景图和字体颜色都可以改变
但是我略微想一下RadioButton完全符合这个需求呀。
下图前面三个是RadioButton , 后面的那个是CheckBox.
但是经过我的测试RadioButton是不符合要求的,因为它在单独使用的情况下只能从非check的状态改变到check的
状态,反过来则不行。于是我有想到了CheckBox,发现这个才是完全符合标准的控件于是就用它了,现在做个笔记避免
以后重复造轮子。
代码如下:
首先是背景和字体的两个drawable文件
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="false" android:drawable="@drawable/tabswitcher_long" /> <item android:state_checked="true" android:drawable="@drawable/tabswitcher_short" /> </selector>
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:color="@android:color/holo_red_light" /> <item android:state_checked="false" android:color="@android:color/black" /> </selector>
然后是布局,布局中主要的用法是去除原生的button字样&是字体居中
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:layout_weight="3"> <RadioButton android:id="@+id/btn_0" android:layout_width="40dp" android:layout_height="40dp" android:background="@drawable/radio" android:button="@null" android:checked="true" android:gravity="center" android:text="1" android:textColor="@drawable/radio_textcolor" android:textSize="17.0sp" /> <RadioButton android:id="@+id/btn_1" android:layout_width="40dp" android:layout_height="40dp" android:background="@drawable/radio" android:button="@null" android:gravity="center" android:text="2" android:textColor="@drawable/radio_textcolor" android:textSize="17.0sp" /> <RadioButton android:id="@+id/btn_2" android:layout_width="40dp" android:layout_height="40dp" android:background="@drawable/radio" android:button="@null" android:gravity="center" android:text="3" android:textColor="@drawable/radio_textcolor" android:textSize="17.0sp" /> <CheckBox android:id="@+id/ckb_0" android:layout_width="40dp" android:layout_height="40dp" android:background="@drawable/radio" android:button="@null" android:gravity="center" android:clickable="false" android:text="4" android:textColor="@drawable/radio_textcolor" android:textSize="17.0sp" /> </LinearLayout>