原文地址: Android MaterialButtonToggleGroup使用 - Stars-One的雜貨小窩 覺得單選框不好看,發現了一個Material里的單選按鈕組,感覺UI還不錯,記下使用 使用 效果: 使用前,得看看是否有material的依賴,如 implementation 'c ...
覺得單選框不好看,發現了一個Material里的單選按鈕組,感覺UI還不錯,記下使用
使用
效果:
使用前,得看看是否有material的依賴,如
implementation 'com.google.android.material:material:1.4.0'
PS: 一般新的Android項目創建都是預設帶上material組件依賴的
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="@+id/toggleGroup"
app:singleSelection="true"
app:checkedButton="@id/mbLanzou"
android:orientation="horizontal"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="wrap_content">
<com.google.android.material.button.MaterialButton
android:id="@+id/mbLanzou"
android:layout_weight="1"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="藍奏雲解析"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/mbLanzouYx"
android:layout_weight="1"
android:layout_width="0dp"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_height="wrap_content"
android:text="藍奏雲優享版解析"/>
</com.google.android.material.button.MaterialButtonToggleGroup>
- checkedButton 預設選中按鈕id
- singleSelection 是否單選
- orientation 元素排列方向
- selectionRequired 是否必須要選中
當 selectionRequired 屬性設置為 true 時,用戶必須選擇組中的至少一個按鈕。如果用戶嘗試取消選擇所有按鈕,MaterialButtonToggleGroup 將自動選擇第一個按鈕。
當 selectionRequired 屬性設置為 false 時,用戶可以不選擇任何按鈕,也可以選擇其中的一個按鈕。
感覺selectionRequired
是應該是結合多選來使用
MaterialButtonToggleGroup
本質上和線性佈局LinearLayout差不多,裡面的元素也可以使layout_weight
權重
關於代碼示例:
//獲取當前選中的按鈕id
toggleGroup.checkedButtonId
//獲取按鈕id列表
toggleGroup.checkedButtonIds
//監聽按鈕選中
toggleGroup.addOnButtonCheckedListener { group, checkedId, isChecked ->
//checkedId為選中按鈕id
if (checkedId == R.id.mbLanzou) {
//判斷選中按鈕之後邏輯
} else {
}
}
//選中某個按鈕
toggleGroup.check(R.id.mbLanzou)
參考
提問之前,請先看提問須知 點擊右側圖標發起提問


