3

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...

1
  • If android databinding library not support this functionality, interesting look at another ways of binding custom data object and layout Commented Dec 28, 2016 at 9:29

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

8 Comments

can you explain: who set data variable of layout? I want to understand this mechanism
I understand how to bind data to layout, but question is: how to use binding mechanism with spinner adapter and set of data objects?
You share your SpinnerAdapter
For strings I use ArrayAdapter. Which adapter used for databindings I don't understand
Then how will you inflate your custom spinner layout for each spinner item without using your custom adapter. Something like this stackoverflow.com/a/8116756/5173119
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.