有時(shí)候我們使用簡單的按鈕切換饭入,大多數(shù)都用button通過設(shè)置他們自身的屬性來展示按鈕的切換效果各吨,這樣會出現(xiàn)很多set方法排苍,在代碼里顯示的很臃腫沦寂,并且不能直觀的通過xml展現(xiàn)出來,記錄一下通過RadioGroup實(shí)現(xiàn)單行按鈕的切換,主要是通過設(shè)置RadioButton的background的屬性來顯示下劃線的效果淘衙,方便實(shí)用传藏,如圖:
1598584265(1).jpg
具體實(shí)現(xiàn):
<RelativeLayout
android:background="#3B4EAF"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginTop="60dp">
<View
android:layout_alignParentBottom="true"
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="3dp"/>
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_first"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/selector_radiobutton"
android:button="@null"
android:checked="true"
android:gravity="center"
android:padding="8dp"
android:text="first"
android:textColor="@drawable/selector_title_color"
android:textSize="24sp"/>
<RadioButton
android:id="@+id/rb_second"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/selector_radiobutton"
android:button="@null"
android:gravity="center"
android:padding="8dp"
android:text="second"
android:textColor="@drawable/selector_title_color"
android:textSize="24sp"/>
<RadioButton
android:id="@+id/rb_third"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/selector_radiobutton"
android:button="@null"
android:gravity="center"
android:padding="8dp"
android:text="third"
android:textColor="@drawable/selector_title_color"
android:textSize="24sp"/>
</RadioGroup>
</RelativeLayout>
selector_radiobutton.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="true">
<layer-list>
<!--底層使用下劃線的顏色填充-->
<item>
<shape>
<solid android:color="#ffffff"/>
</shape>
</item>
<!--上面覆蓋一層距離底層的底部3dp,填充白色。兩層疊加一起就形成了一條下劃線效果彤守,原理自行腦補(bǔ)-->
<item android:bottom="3dp">
<shape>
<solid android:color="#ff0000"/>
</shape>
</item>
</layer-list>
</item>
<item
android:drawable="@android:color/transparent">
</item>
</selector>
selector_title_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:color="#ffffff" android:state_checked="true">
</item>
<item
android:color="#000000" android:state_pressed="true">
</item>
<item
android:color="#000000">
</item>
</selector>
更復(fù)雜的效果還要根據(jù)具體情況來實(shí)現(xiàn)