Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use View Binding on custom views

View Binding got released as part of Android Jetpack

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

My question is, how to use view binding with custom views. Google documentation 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.

like image 405
Emad Razavi Avatar asked Feb 27 '20 12:02

Emad Razavi


People also ask

Should I use view binding?

ViewBinding is always null safe and type-safe, which supports both Java and Kotlin. ViewBinding is introduced in the Gradle version 3.6 and above (which comes with the Android Studio 4.0, only gradle 3.6). ViewBinding also helps to reduce the boilerplate code, hence reducing the code redundancy.

Can you create custom views How?

Creating custom views. By extending the View class or one of its subclasses you can create your custom view. For drawing view use the onDraw() method. In this method you receive a Canvas object which allows you to perform drawing operations on it, e.g. draw lines, circle, text or bitmaps.

What is Databindingutil in Android?

Inflates a binding layout and returns the newly-created binding for that layout. static <T extends ViewDataBinding> T. inflate(LayoutInflater inflater, int layoutId, ViewGroup parent, boolean attachToParent) Inflates a binding layout and returns the newly-created binding for that layout.


1 Answers

Just inform the root, and whether you want to attach to it

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

or

init { // inflate binding and add as view     binding = ResultProfileBinding.inflate(LayoutInflater.from(context), this, true) } 

which inflate method to use will depend on the root layout type in xml.

like image 135
Androiderson Avatar answered Oct 12 '22 06:10

Androiderson