20

I am having trouble in implementing view binding in a Custom Dialog Layout. Is it possible?

 private fun showCustomDialog(title: String) {
    val dialog = Dialog(activity)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)

    dialog.setContentView(R.layout.custom_layout)

    val body = dialog.findViewById(R.id.body) as TextView
    body.text = title

    val noBtn = dialog.findViewById(R.id.noBtn) as TextView
    yesBtn.setOnClickListener {
        dialog.dismiss()
    }

    val yesBtn = dialog.findViewById(R.id.yesBtn) as Button
    noBtn.setOnClickListener { dialog.dismiss() }
    dialog.show()

}

4 Answers4

43

It is possible.

CustomDialogBinding binding = CustomDialogBinding 
          .inflate(LayoutInflater.from(getContext()));
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setView(binding.getRoot());

Where CustomDialogBinding is the name of the view binding file for your custom layout

kotlin

val bind :CustomDialogBinding = CustomDialogBinding .inflate(inflater)
dialog.setContentView(bind.root)
SABANTO
  • 1,316
  • 9
  • 24
13

Code:

val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val binding = CustomDialogLayoutBinding.inflate(inflater)
dialog.setContentView(binding.root)
Ghayas
  • 1,266
  • 10
  • 17
4

Example:

val dialogBinding = DialogCustomBinding.inflate(layoutInflater)
dialog.setView(dialogBinding.root)
Jimmy ALejandro
  • 434
  • 5
  • 11
0

Similar way to the first answer, including a few extra lines. Assumes your binding is DialogReviewBinding.

val inflater = activity.layoutInflater
val dialogBinding = DialogReviewBinding.inflate(inflater)
val dialog = AlertDialog.Builder(activity).create()
dialog.setView(dialogBinding.root)
dialog.show()

And this is surrounded by a activity?.let { activity -> } block