I have a question about using viewBinding
in a dialog fragment, that uses a custom view. Is there a standard way of doing this?
My code that uses findViewById()
for the dialog fragment but I would like to use viewbinding as that is standard across the rest of my project.
class WifiHandlerDialogFragment(private val wifiErrorType: Int): DialogFragment() {
private var _binding: DialogWifiHandlerBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
_binding = DialogWifiHandlerBinding.inflate(LayoutInflater.from(context))
val dialog = activity?.let {
Dialog(it)
}
if(dialog != null) {
dialog.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialog.window?.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
dialog.setContentView(R.layout.dialog_wifi_handler)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
val positiveButton = dialog.findViewById<Button>(R.id.positive_button) // really want to change this to use binding
val closeButton = dialog.findViewById<Button>(R.id.close_button) // really want to change this to use binding
val dialogMessage = dialog.findViewById<TextView>(R.id.dialog_message)
positiveButton.setOnClickListener {
startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
}
closeButton.setOnClickListener {
dismiss()
}
dialogMessage.text = when (wifiErrorType) {
1 -> getString(R.string.connection_dialog_op1)
2 -> getString(R.string.connection_dialog_op2)
3 -> getString(R.string.connection_dialog_op3)
else -> getString(R.string.error)
}
}
return dialog!!
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
I was trying to use binding.closebutton
in the onCreateDialog()
function but that us not working (I assume due to fragment lifecycle).
I have looked at these questions:
How to correctly use Android View Binding in DialogFragment?
Android DialogFragment onViewCreated not called
But still haven't worked out what is the best way to achieve this (also my first time using viewbinding
coming from kotlin synthetics).