Search code examples
androidkotlintextviewdialogfragmentmaterial-dialog

Can't set text on text view in dialog fragment


I have a dialog fragment and I use databinding to bind views.

I can't set text on a text view after the dialog is created.

Here is my code :

class MyDialogFragment : DialogFragment() {

    private lateinit var layout : FragmentMyDialogBinding

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        layout = FragmentMyDialogBinding.inflate(inflater,container,false)
        return layout.root
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {


        layout = FragmentMyDialogBinding.inflate(LayoutInflater.from(requireContext()))

        layout.textView.text = "Initial text"

        layout.button.setOnClickListener{
        
        layout.textView.text = "Text changed"
        
        Log.wtf("Text","${layout.textView.text}")

        // Log shows the changed text but it is not visible on the ui.
        
        }
        

        val builder = MaterialAlertDialogBuilder(requireContext(), R.style.RoundShapeTheme)


        builder.setView(layout.root)

        return builder.create()
    }

}

Log shows the changed text but it is not visible on the UI.

Does anybody have a solution for this ?


Solution

  • I just tested your code and it is resolved by removing the onCreateView().. You already use onCreateDialog() and it's enough for setting the binding object.

    The layout is inflated twice, and probably the textView gets changed on the layout that is not on the UI. That is probably because the onCreateView() gets called after onCreateDialog(). So, when you change the text in the onCreateDialog() inflated layout the change is not appeared because the inflated layout by onCreateView() is laid on top of it.