Android復選框CheckBox與開關按鈕Switch及單選按鈕RadioButton使用示例詳解
前言
CompoundButton在XML文件中主要使用下面兩個屬性。
- checked:指定按鈕的勾選狀態(tài),true表示勾選,false則表示未勾選,默認為未勾選。
- button:指定左側勾選圖標的圖形資源,如果不指定就使用系統(tǒng)的默認圖標。
CompoundButton在java代碼中主要使用下列4種方法。
- setChecked:設置按鈕的勾選狀態(tài)。
- setButtonDrawable:設置左側勾選圖標的圖形資源。
- setOnCheckedChangeListener:設置勾選狀態(tài)變化的監(jiān)聽器。
- isChecked:判斷按鈕是否勾選。
一、復選框CheckBox
<CheckBox android:id="@+id/ck_system" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" android:text="系統(tǒng)CheckBox"/>
二、開關按鈕Switch
Switch是開關按鈕,它在選中與取消選中時可展現(xiàn)的界面元素比復選框豐富。
Switch控件新添加的XML屬性說明如下:
- textOn:設置右側開啟時的文本。
- textOff:設置左側關閉時的文本。
- track:設置開關軌道的背景。
- thumb:設置開關標識的圖標。
<Switch android:id="@+id/sw_status" android:layout_width="80dp" android:layout_height="30dp" android:padding="5dp"/>
三、單選按鈕RadioButton
單選按鈕要在一組按鈕種選擇其中一項,并且不能多選,這要求有個容器確定這組按鈕的范圍,這個容器便是單選組RadioGroup。
RadioGroup實際上是個布局,同一組RadioButton都要放在同一個RadioGroup節(jié)點下,除了RadioButton,也允許放置其他控件。
單選組的用法
判斷選中了哪個單選按鈕,通常不是監(jiān)聽某個單選按鈕,而是監(jiān)聽單選組的選中事件。
RadioGroup常用的3個方法:
- check:選中指定資源編號的單選按鈕。
- getCheckedRadioButtonId:獲取選中狀態(tài)單選按鈕的資源編號。
- setOnCheckedChangeListener:設置單選按鈕勾選變化的監(jiān)聽器。
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="請選擇性別"/> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content"> <RadioButton android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="男"/> <RadioButton android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="女"/> </RadioGroup>
到此這篇關于Android復選框CheckBox與開關按鈕Switch及單選按鈕RadioButton使用示例詳解的文章就介紹到這了,更多相關Android按鈕內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Android使用WebView實現(xiàn)文件下載功能
這篇文章主要為大家詳細介紹了Android使用WebView實現(xiàn)文件下載功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05Android不規(guī)則封閉區(qū)域填充色彩的實例代碼
這篇文章主要介紹了Android不規(guī)則封閉區(qū)域填充色彩的實例代碼, 具有很好的參考價值,希望對大家有所幫助,一起跟隨小編過來看看吧2018-05-05android kotlin集成WorkManager實現(xiàn)定時獲取數(shù)據(jù)的步驟
在Android中使用Kotlin集成WorkManager來實現(xiàn)定時獲取數(shù)據(jù)是一個很常見的需求,下面給大家分享android kotlin集成WorkManager實現(xiàn)定時獲取數(shù)據(jù)的步驟,感興趣的朋友跟隨小編一起看看吧2024-08-08