Updated 18 December 2016
I was working on Data binding in my android application for quite some time and thought that there is only one method to bind data is via Objects or variables i.e. for every single value to bind with the layout I either have to save it to a variable or make an object. Also for some functionality and feature we still need View ID defined in layout in our Activity/Fragment. So thought of it as a limitation of data binding but I was wrong.
Android Developers at Google must have thought of it initially and yes you can access the View ID defined in your XML in your Activity/fragment without using findViewById(). And its very simple as well, you don’t have to do anything your Binding class has already did it for you.
All the View ID (s) you have declared in your XML are by default converted in a Variable in your Binding class, its name is the CamelCase version of the ID you defined like for android:id=”@+id/item_view” the generated variable will be itemView. Now you can access the variable through binding variable and can apply and method on it or whatever is your requirement.
For example if I have a layout info_layout like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:apps="http://schemas.android.com/apk/res-auto"> <LinearLayout android:id="@+id/main_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/light_grey" android:paddingBottom="1dp" android:paddingEnd="1dp" android:paddingRight="1dp" android:paddingTop="1dp"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:textStyle="italic"/> </LinearLayout> </layout> |
Then in your activity you can either inflate the layout wherever you want like
1 2 3 4 5 6 7 8 |
InfoLayoutBinding bind= InfoLayoutBinding.inflate(getLayoutInflater() , info_layout_container,true); bind.mainView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { //your action } }); bind.text.setText("Successfully Bind"); |
Or you can set it with replacing setContentView() of your Activity as
1 2 3 4 5 6 7 8 |
InfoLayoutBinding bind = DataBindingUtil.setContentView(this, R.layout.info_layout); bind.mainView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { //your action } }); bind.text.setText("Successfully Bind"); |
If you have two view in your XML that become same after applying CamelCase on them then also you don’t need to worry. Because DataBinding can deal with it too. it will give one View as CamelCase name and other one with added numeric one after that i.e. MainView and MainView1. So what do you think about data binding now. Isn’t it cool?
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.