Sergei Bubenshchikov
Sergei Bubenshchikov

Reputation: 5371

How to bind custom object to spinner layout using databinding library?

I wish to bind my object to spinner row layout by android databinding library. Post 1 and Post 2 not explained how I can use databinding and how to bind multiple fields (not only one string) of data object.

My data object looks like:

class Data{
    public final String imageUri;
    public final String title;
    public final int totalCount;
}

Layout I wish looks as:

<!-- horisontal orientation -->
<LinearLayout>
    <!-- Icon -->
    <ImageView/>

    <!-- Title -->
    <TextView/>

    <!-- TotalCount -->
    <TextView/>
</LinearLayout>

and how it bind I don't know...

Upvotes: 3

Views: 1864

Answers (1)

Sasank Sunkavalli
Sasank Sunkavalli

Reputation: 3964

You have to wrap your entire layout in layout tag to use Data Binding.This way you can assign the Model to your View So this should be your layout.

<layout>
   <data>
     <variable name="data" type="your.packagename.Data">
     </variable> 
   </data>
   <!-- horisontal orientation -->
   <LinearLayout>
     <!-- Icon -->
     <ImageView
       android:src="@{data.imageUri}"/>

     <!-- Title -->
     <TextView
       android:text="@{data.title}"/>

     <!-- TotalCount -->
     <TextView
       android:text="@{data.totalCount}"/>

  </LinearLayout>
</layout>

Lets assume your are using Activity to show the Spinner & your layout name is custom_spinner.xml . Then here is how you set the data to layout. After setting the Spinner Adapter, here is what you need to do

Data data; // Data object
CustomSpinnerBinding binding = DataBindingUtil.inflate(R.layout.custom_spinner);
binding.setData(data);

This should be your custom Adapter

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    CustomSpinnerBinding binding = DataBindingUtil.inflate(R.layout.custom_spinner);
    binding.setData(dataList.get(position)); // you should pass dataList as an argument in Custom Adapter constructor
}

Upvotes: 2

Related Questions