Search code examples
androidkotlinandroid-viewbinding

View Binding in DialogFragment with custom layout in Kotlin


I loved using Kotlin synthetic for its simplicity and code elegance but now they made it depricated and push you to use those ugly view bindings.

There are plenty of answers on how to use it in activites and Fragments, but could not find any examples for custom layout alert dialogs.

Here is the code which worked perfectly with Kontlin synthetic.

import kotlinx.android.synthetic.main.dialog_reward.*

class RewardDialog: DialogFragment() {
    private var mView: View? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return mView
    }
    
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            mView = it.layoutInflater.inflate(R.layout.dialog_reward, null)
            AlertDialog.Builder(it).apply {
                setView(mView)
            }.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        //reference layout elements by name freely
        
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        mView = null
    }
}

How do I migrate this to view bindings?


Solution

  • I have ended up with the following solution. Thanks to @Kishan Maurya for the hint about binding.root.

    private var _binding: DialogRewardBinding? = null
    private val binding get() = _binding!!
    
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.run {
            //initiate the binding here and pass the root to the dialog view
            _binding = DialogRewardBinding.inflate(layoutInflater).apply {
                //reference layout elements by name freely here
            }
            AlertDialog.Builder(this).apply {
                setView(binding.root)
            }.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }
    
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }