I have a MaterialButtonToggleGroup inside an alert dialog with 2 buttons that looks like: Toggle
I am having trouble getting sharedPreferences to work so that the user's choice is still selected when they return to the dialog.
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:singleSelection="true"
app:selectionRequired="true"
android:layout_gravity="center"
android:layout_marginBottom="50dp"
app:checkedButton="@+id/on">
<Button
style="?attr/materialButtonOutlinedStyle"
android:id="@+id/on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
app:cornerRadius="15dp"
android:textSize="20sp"
android:text="@string/on" />
<Button
style="?attr/materialButtonOutlinedStyle"
android:id="@+id/off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cornerRadius="15dp"
android:textColor="@color/black"
android:textSize="20sp"
android:text="@string/off" />
</com.google.android.material.button.MaterialButtonToggleGroup>
view.toggleButton?.addOnButtonCheckedListener { toggleButton, checkedId, isChecked ->
if (!isChecked) return@addOnButtonCheckedListener
if (checkedId == R.id.on) {
//do something
}
if (checkedId == R.id.off) {
//do something
}
}
private fun retrieveData() {
// what goes here?
}
override fun onResume() {
super.onResume()
retrieveData()
}
First you need to declare the
SharedPreferences, initialize it and then saving its value on the user action and retrieve the value when the fragment is initialized (onViewCreated), here's the snippet: