Mini apuntes de como implementar ViewBinding en un DialogFragment usando Android Studio y Kotlin.
Dependencias
En archivo gradle a nivel de aplicación añadir dentro del bloque android
android {
...
buildFeatures {
viewBinding true
}
}
Layout
Crear archivo sdetail_dialog_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_first_fragment"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
View Binding en Dialog Fragment
En la implementación de Dialog Fragment es similar al Fragment pero extendiendo de DialogFragment.
class DetailDialogFragment : DialogFragment() {
private var _binding: FragmentDetailBinding? = null
private val binding get() = _binding!!
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
_binding = FragmentDetailBinding.inflate(layoutInflater)
val dialog = MaterialAlertDialogBuilder(
requireActivity()
).apply {
setView(binding.root)
setPositiveButton(getString(android.R.string.ok)) { _, _ ->
}
setOnKeyListener { _, keyCode, keyEvent ->
if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.action == KeyEvent.ACTION_UP) {
dismiss()
true
} else false
}
}.create()
return dialog
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
Llamar el DialogFragment
Des de donde queremos llamar el dialog fragment
private fun showSubmitFeedbackDialog() {
val dialogTag = "DETAIL_PROPERTY"
val navHostFragment = requireActivity().supportFragmentManager.fragments.first() as NavHostFragment
if (navHostFragment.childFragmentManager.findFragmentByTag(dialogTag) != null) return
val dialog = DetailDialogFragment()
dialog.show(navHostFragment.childFragmentManager, dialogTag)
}
showSubmitFeedbackDialog()