Step 1 - Enable DataBinding in your gradle file.
- android {
- ...
- ...
- dataBinding {
- enabled = true
- }
Step 2 - Define POJO/Model class
- public class PersonModelClass
- {
- String name,designation,image_url;
-
- public PersonModelClass(String name, String designation, String image_url) {
- this.name = name;
- this.designation = designation;
- this.image_url = image_url;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDesignation() {
- return designation;
- }
-
- public void setDesignation(String designation) {
- this.designation = designation;
- }
-
- public String getImage_url() {
- return image_url;
- }
-
- public void setImage_url(String image_url) {
- this.image_url = image_url;
- }
- }
Step 3 - Define custom binding class.
- public class CustomBindingAdapter
- {
- @BindingAdapter({"bind:image_url"})
- public static void loadImage(ImageView imageView,String url)
- {
- Picasso.with(imageView.getContext()).load(url).resize(200,200).into(imageView);
- }
- }
Here I have used Picasso for image loading, you can replace this code with your own image loader like Glide, UniversaImageLoader etc.
Step 4
Create layout file and add the new image_url attribute to your ImageView. Custom attributes need to use the app namespace instead of android.
- <?xml version="1.0" encoding="utf-8"?>
- <layout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto">
-
- <data>
-
- <variable
- name="person"
- type="<package name>.PersonModelClass"></variable>
- </data>
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:gravity="center"
- android:orientation="horizontal">
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- app:image_url="@{person.image_url}" />
-
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginLeft="10dp"
- android:orientation="vertical">
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@{person.name}"
- android:textAppearance="?android:attr/textAppearanceLarge" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@{person.designation}" />
-
- </LinearLayout>
- </LinearLayout>
- </layout>
Step 5 - Finally in your activity class set view with DataBindingUtils.
- public class MainActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- ActivityMainBinding binding= DataBindingUtil.setContentView(this,R.layout.activity_main);
- PersonModelClass model=new PersonModelClass("Ravi Rupareliya","Android Developer","<image url>");
- binding.setPerson(model);
- }
- }