How to use View Binding on custom views

Emi Raz :

View Binding got released with v3.6.

Docs: https://developer.android.com/topic/libraries/view-binding

My question is, how to use view binding with custom views. google docus has only show-cased Activity and fragment.

I tried this, but nothing was shown.

LayoutInflater inflater = LayoutInflater.from(getContext());

And then, I used this one, but again, no luck.

LayoutInflater inflater = (LayoutInflater)
            getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

I guess, maybe I don't target the correct layout inflater for my view but not sure about it.

Pavneet_Singh :

To use the view binding, you need to use the generated binding class not the LayoutInflater, for example, if the layout name is result_profile.xml then you need to use ResultProfileBinding as:

class CustomView @kotlin.jvm.JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private lateinit var binding: ResultProfileBinding

    init { // inflate binding and add as view
        binding = ResultProfileBinding.inflate(LayoutInflater.from(context))
        addView(binding.root)
    }

}
  1. Auto generated class : result_profile.xml -> ResultProfileBinding(name of layout, appended with Binding )
  2. Inflate the binding

    ResultProfileBinding.inflate(LayoutInflater.from(context))
    
  3. Use addView to add the view in the hierarchy as:

    addView(binding.root)
    

Note: If you are extending from ConstraintLayout(is the parent class) then use constraint set

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12285&siteId=1