日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android復選框CheckBox與開關按鈕Switch及單選按鈕RadioButton使用示例詳解_Android

作者:Shewyoo ? 更新時間: 2022-11-17 編程語言

前言?

CompoundButton在XML文件中主要使用下面兩個屬性。

  • checked:指定按鈕的勾選狀態,true表示勾選,false則表示未勾選,默認為未勾選。
  • button:指定左側勾選圖標的圖形資源,如果不指定就使用系統的默認圖標。

CompoundButton在java代碼中主要使用下列4種方法。

  • setChecked:設置按鈕的勾選狀態。
  • setButtonDrawable:設置左側勾選圖標的圖形資源。
  • setOnCheckedChangeListener:設置勾選狀態變化的監聽器。
  • isChecked:判斷按鈕是否勾選。

一、復選框CheckBox

    <CheckBox
        android:id="@+id/ck_system"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="系統CheckBox"/>

二、開關按鈕Switch

Switch是開關按鈕,它在選中與取消選中時可展現的界面元素比復選框豐富。

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節點下,除了RadioButton,也允許放置其他控件。

單選組的用法

判斷選中了哪個單選按鈕,通常不是監聽某個單選按鈕,而是監聽單選組的選中事件。

RadioGroup常用的3個方法:

  • check:選中指定資源編號的單選按鈕。
  • getCheckedRadioButtonId:獲取選中狀態單選按鈕的資源編號。
  • setOnCheckedChangeListener:設置單選按鈕勾選變化的監聽器。
    <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>

原文鏈接:https://blog.csdn.net/Tir_zhang/article/details/126973628

欄目分類
最近更新