我有一个对话框可以选择一周中的多天,如下所示:
class DialogSettingsEnabledDays : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity.let {
val selectedDaysValue = BooleanArray(7) { _ -> false }
val selectedDaysIndex = ArrayList<Int>()
val daysToIndexMap = mutableMapOf<String, Int>()
val indexToDaysMap = mutableMapOf<Int, String>()
val daysArray = resources.getStringArray(R.array.days_medium)
for (i in 0..6) {
daysToIndexMap[daysArray[i]] = i
indexToDaysMap[i] = daysArray[i]
}
val prefs = it!!.getSharedPreferences(getString(R.string.shared_prefs_settings), Context.MODE_PRIVATE)
val selectedDaysString = prefs.getString("enabled_days", getString(R.string.default_enabled_days))
val selectedDays = selectedDaysString!!.split(", ")
for (day in selectedDays) {
selectedDaysValue[daysToIndexMap.getValue(day)] = true
selectedDaysIndex.add(daysToIndexMap.getValue(day))
}
val enabledDaysBuilder = AlertDialog.Builder(it)
enabledDaysBuilder
.setTitle(R.string.settings_enabled_days)
.setMultiChoiceItems(R.array.days_long, selectedDaysValue) { _, which, isChecked ->
if (isChecked)
selectedDaysIndex.add(which)
else if (selectedDaysIndex.contains(which))
selectedDaysIndex.remove(Integer.valueOf(which))
}
.setPositiveButton(R.string.dialog_ok) { _, _ ->
if (selectedDaysIndex.isEmpty()) {
Toast.makeText(it, "Select atleast one day !!", Toast.LENGTH_SHORT).show()
} else {
selectedDaysIndex.sort()
val selectedDaysList = mutableListOf<String>()
for (i in selectedDaysIndex) {
selectedDaysList.add(indexToDaysMap.getValue(i))
}
val editor = prefs.edit()
editor
.putString("enabled_days", selectedDaysList.joinToString())
.apply()
val enabledDays = it.findViewById<LinearLayout>(R.id.settings_enabled_days)
enabledDays.findViewById<TextView>(R.id.secondary_text).text = selectedDaysList.joinToString()
}
}
.setNegativeButton(R.string.dialog_cancel) { _, _ -> /* do nothing */ }
enabledDaysBuilder.create()
}
}
}
我从我的活动中以这种方式调用此对话框:
findViewById<LinearLayout>(R.id.settings_enabled_days)
.setOnClickListener {
DialogSettingsEnabledDays().show(this.supportFragmentManager, null)
}
我的问题是我选择的日期在轮换时重置为默认值。默认情况下,我的意思是存储在 中的选择,SharedPreferences
即selectedDaysValue
. .setMultiChoiceItems
假设这些是弹出对话框的选定日期:
Mon, Tue, Wed, Thu, Fri
现在,我将选择更改为:
Mon, Tue
但是,当我旋转手机时,选择会恢复为默认值:
Mon, Tue, Wed, Thu, Fri
如何保留我对方向更改的选择?因为在我见过的一些应用程序中,对话框选择在旋转时保持不变。