-
Notifications
You must be signed in to change notification settings - Fork 0
Applying Data Binding for Views
Android has now released a stable data-binding library which allows you to connect views with data in a much more powerful way than was possible previously. Applying data binding can improve your app by removing boilerplate for data-driven UI and allowing for two-way binding between views and data objects.
The Data Binding Library is a support library that is compatible with all recent Android versions.
To get started with data binding, we need to make sure to download the support repository in the Android SDK manager.
To configure your app to use data binding, add the dataBinding
element to your app/build.gradle
file:
apply plugin: 'com.android.application'
android {
// Previously there
// Add this next line
dataBinding.enabled = true // <----
// ...
The most basic thing we get with data binding is the elimination of findViewById
. To enable this to work for a layout file, first we need to change the layout file by making the outer tag instead of whatever ViewGroup you use:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</layout>
The layout
container tag tells Android Studio that this layout should take the extra processing during compilation time to find all the interesting Views and note them for use with the data binding library. Now, we can use the Binding
object to access the view. In our activity, we can now inflate the layout content using the binding:
public class MainActivity extends AppCompatActivity {
// Store the binding
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the content view (replacing `setContentView`)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
// Store the field now if you'd like without any need for casting
TextView tvLabel = binding.tvLabel;
tvLabel.setAllCaps(true);
// Or use the binding to update views directly on the binding
binding.tvLabel.setText("Foo");
}
}
Note that this binding object is generated automatically with the following rules in place:
- Layout file
activity_main.xml
becomesActivityMainBinding
binding object - View IDs within a layout become variables inside the binding object (i.e
binding.tvLabel
)
The binding process makes a single pass on all views in the layout to assign the views to the fields. Since this only happens once, this can actually be faster than calling findViewById
.
Refer to this guide for more details about bindings and inflating views.
The simplest binding is to automatically load data from an object into a view directly using a new syntax in the template. For example, suppose we want to display a user's name inside a TextView
. Assuming a simple user class:
public class User {
public String firstName;
public String lastName;
}
Next, we need to wrap our existing layout inside a <layout>
tag to indicate we want data binding enabled:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvFullName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World" />
</RelativeLayout>
</layout>
Next, we need to indicate that we want to load data from a particular object by declaring variable
nodes in a data
section of the <layout>
:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable name="user" type="com.example.User"/>
</data>
<!-- ... rest of layout here -->
</layout>
The user
variable within the data block describes a property that can now be used within this layout. Next, we can now reference this object inside of our views using @{variable.field}
syntax such as:
<TextView
android:id="@+id/tvFullName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{user.firstName + " " + user.lastName}' />
We can use conditional logic and other operations as part of the binding expression language for more complex cases. Finally, we need to assign that user data variable to the binding at runtime:
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the `activity_main` layout
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
// Create or access the data to bind
User user = new User("Sarah", "Gibbons");
// Attach the user to the binding
binding.setUser(user);
}
}
That's all! When running the app now, you'll see the name is populated into the layout automatically:
If you want to have a two-way binding between the view and the data source, check out this handy 2-way data binding tutorial.
- https://developer.android.com/topic/libraries/data-binding/index.html
- https://medium.com/google-developers/no-more-findviewbyid-457457644885#.p1ie9j52a
- https://realm.io/news/data-binding-android-boyar-mount/
- https://www.captechconsulting.com/blogs/android-data-binding-tutorial
- http://www.survivingwithandroid.com/2015/08/android-data-binding-tutorial-2.html
Created by CodePath with much help from the community. Contributed content licensed under cc-wiki with attribution required. You are free to remix and reuse, as long as you attribute and use a similar license.
Finding these guides helpful?
We need help from the broader community to improve these guides, add new topics and keep the topics up-to-date. See our contribution guidelines here and our topic issues list for great ways to help out.
Check these same guides through our standalone viewer for a better browsing experience and an improved search. Follow us on twitter @codepath for access to more useful Android development resources.
Interested in ramping up on Android quickly?
(US Only) If you are an existing engineer with 2+ years of professional experience in software development and are serious about ramping up on Android quickly, be sure to apply for our free evening 8-week Android bootcamp.
We've trained over a thousand engineers from top companies including Apple, Twitter, Airbnb, Uber, and many others leveraging this program. The course is taught by Android experts from the industry and is specifically designed for existing engineers.
Not in the United States? Please fill out our application of interest form and we’ll notify you as classes become available in your area powered by local organizers.