如何对切换按钮进行分组以控制选择?



我的应用程序内有三个SwitchMaterial开关,需要相互通信。我想根据当前选择来控制选择。例如,如果第一个开关设置为 true,则接下来的两个开关也应设置为 true。如果第二个和第三个开关设置为 true,则第一个开关应设置为 true,依此类推。我知道我可以使用 if 和 else 语句来控制这一点,但是有没有办法将它们组合在一起以便于实现?

<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/switch_all_holes_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Select All Holes"
android:textSize="25dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toTopOf="@id/switch_front_nine_btn"
android:paddingStart="10dp"
android:paddingBottom="10dp"/>
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/switch_front_nine_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="Select Front Nine"
android:textSize="25dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toTopOf="@id/switch_back_nine_btn"
android:paddingStart="10dp"
android:paddingBottom="10dp"/>
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/switch_back_nine_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="Select Back Nine"
android:textSize="25dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toTopOf="@id/select_first_nine_btn"
android:paddingStart="10dp"
android:paddingBottom="10dp"/>

在活动中,您需要引用开关,并在激活一个开关后应用所需的更改

firstButton.setOnCheckedChangeListener(
CompoundButton.OnCheckedChangeListener { buttonView, isChecked -> changeOtherButtons()}
)

您可以在 changeOtherButtons(( 方法中更新其他按钮 - 您需要为每个按钮实现一个方法,或给出方法参数等。

最新更新