I have a SettingsActivity.kt as follows:
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setLayout()
setListeners()
}
private fun setLayout() {/* fun to set layout* /}
private fun setListeners() {
val day = findViewById<LinearLayout>(R.id.settings_day)
day.setOnClickListener { myDialog() }
/* some other dialogs created in similar way */
}
private fun myDialog() {
val prefs = getSharedPreferences("SETTINGS", Context.MODE_PRIVATE)
var selectedDay = prefs.getInt("day", 1)
val myBuilder = AlertDialog.Builder(this)
myBuilder
.setTitle(R.string.settings_day)
.setSingleChoiceItems(R.array.days, selectedDay) { _, which ->
selectedDay = which
}
.setPositiveButton(R.string.dialog_ok) { _, _ ->
val editor = prefs.edit()
editor
.putInt("day", selectedDay)
.apply()
}
.setNegativeButton(R.string.dialog_cancel) { _, _ -> /* do nothing */ }
val theDialog = myBuilder.create()
theDialog.show()
}
}
When the orientation of device changes, the dialog disappears.
I think I have to use DialogFragment, but I have some problems, the official guide at https://developer.android.com/guide/topics/ui/dialogs#kotlin doesn't explain much. I am confused where to place the code.
Most of the tutorials on DialogFragment are either for custom layout or in java.
So, can somebody tell me how to convert my code so as to use DialogFragment. I am having difficulty to understand it from examples.
Create a subclass of DialogFragment
and override onCreateDialog()
to return your AlertDialog
, e.g. just move your myDialog
code up to myBuilder.create()
there.
When you want do display your DialogFragment
, instantiate it and call show on it, passing in a reference to the fragment manager and an (optional) tag. For example:
MyDialogFragment().show(requireFragmentManager(), null)