Apuntes de como crear un cuadro de diálogo que muestre una lista selecionable mediante RadioButtons.

Al selecionar uno se cierre el cuadro de diálogo, se mantenga permamente a la vista en el caso de rotar el dispositivo y devuelve el elemento selecionado des de donde se ha llamado.
SingleChoiceAlertDialog
class SingleChoiceAlertDialog : DialogFragment() {
interface OnDialogSelectorListener {
fun onSelectedOption(dialogId: Int)
}
var mDialogSelectorCallback: OnDialogSelectorListener? = null
fun newInstance(title: String, values: Array<String>, selected: Int = -1): SingleChoiceAlertDialog? {
val dialog = SingleChoiceAlertDialog()
val args = Bundle()
args.putString("title", title)
args.putStringArray("values", values)
args.putInt("selected", selected)
dialog.arguments = args
return dialog
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val args = requireArguments()
val title = args.getString("title")
val values = args.getStringArray("values")
val selectedIndex = args.getInt("selected")
val builder: AlertDialog.Builder = AlertDialog.Builder(requireActivity())
builder.setSingleChoiceItems(values, selectedIndex) { _, which ->
//val item = values?.get(which)
mDialogSelectorCallback?.onSelectedOption(which)
dialog?.dismiss()
}
builder.setTitle(title)
return builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
Su uso
val modalDialog = SingleChoiceAlertDialog().newInstance(
"Ordenar por",
resources.getStringArray(R.array.sort_array),
0
)
modalDialog?.mDialogSelectorCallback = this
modalDialog?.show(requireActivity().supportFragmentManager, "singleChoiceDialog")
Para interceptar el elemento selecionado se debe escuchar el SingleChoiceAlertDialog.OnDialogSelectorListener
class ListPackagesFragment : Fragment(), SingleChoiceAlertDialog.OnDialogSelectorListener {
...
override fun onSelectedOption(dialogId: Int) {
//@Todo selecionado el dialogID
}
}