Android DataBinding - bind Spinner with custom adapter

Viewed 3838

I want to bind my Spinner with custom adapter used. I need 2-way binding. I'm not sure how to do that with custom adapter?

My spinner is defined in xml:

 <Spinner
                android:id="@+id/add_event_category_spinner"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="8dp"
                android:prompt="@string/spinner_category_title"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/TextView"/>

Custom adapter:

public class EventCategoryAdapter extends ArrayAdapter<Category>
{
    private Context context;
    private List<Category> values;

    public EventCategoryAdapter (@NonNull Context context, int textViewResourceId, @NonNull List<Category> values)
    {
        super(context, textViewResourceId, values);
        this.context = context;
        this.values = values;
    }

    public int getCount()
    {
        return values.size();
    }

    public Category getItem(int position)
    {
        return values.get(position);
    }

    public long getItemId(int position)
    {
        return position;
    }


    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        TextView label = new TextView(context);
        label.setText(values.get(position).getName());

        return label;
    }

    @NonNull
    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater vi = LayoutInflater.from(getContext());
        convertView = vi.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
        CheckedTextView label = (CheckedTextView) convertView.findViewById(android.R.id.text1);

        label.setText(values.get(position).getName());


        return label;
    }
}

So, as you can see, adapter List collection to fill items. OnClick listener gives my Category object selected and Spinner displays only Category.Name field as label. Now I need to bind my spinner with data binging to avoid using onItemSelected event. Instead, selected item should be bound and automatically populated to my view model. I need 2-way binding, so changing view model should also trigger set selection for my spinner.

I know how to bind text views, labels and recycler views (for lists), but I'm not sure how to bind adapter for my spinner. Any tips?

My attempt:

<android.support.v7.widget.AppCompatSpinner
            android:id="@+id/spinner"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginTop="7dp"
            app:layout_constraintTop_toBottomOf="@+id/editText4"
            android:layout_marginRight="8dp"
            android:layout_marginLeft="8dp"
            android:entries="@{user.categories}"
            android:selectedItemPosition="@={user.selectedCategoryPosition}"/>

And User class:

@InverseBindingMethods({@InverseBindingMethod(type = AppCompatSpinner.class, attribute = "android:selectedItemPosition")})
public class User extends BaseObservable
   {
    public List<Category> categories;

    Category category = null;

    @Bindable
    public Category getCategory()
    {
        return category;
    }

    public void setCategory(Category category)
    {
        this.category = category;
        notifyPropertyChanged(BR.category);
    }

    Integer selectedCategoryPosition = 0;


    @BindingAdapter("selectedItemPositionAttrChanged")
    void setSelectedItemPositionListener(AppCompatSpinner view, final InverseBindingListener selectedItemPositionChange)
    {
        if (selectedItemPositionChange == null)
        {
            view.setOnItemSelectedListener(null);
        }
        else
        {
            view.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
            {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
                {
                    selectedItemPositionChange.onChange();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent)
                {

                }
            });
        }
    }

    @InverseBindingAdapter(attribute = "selectedItemPosition")
    Integer getSelectedItemPosition(AppCompatSpinner spinner)
    {
        return spinner.getSelectedItemPosition();
    }


    @Bindable
    public Integer getSelectedCategoryPosition()
    {
        return selectedCategoryPosition;
    }

    public void setSelectedCategoryPosition(Integer selectedCategoryPosition)
    {
        this.selectedCategoryPosition = selectedCategoryPosition;
        notifyPropertyChanged(BR.selectedCategoryPosition);
        category = categories.get(selectedCategoryPosition);
    }
}

In main activity:

@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        User user = new User();
        activityMainBinding.setUser(user);

Now I'm getting error:

Error:Execution failed for task ':app:transformJackWithJackForDebug'.

com.android.jack.ir.JNodeInternalError: java.lang.Exception: java.lang.RuntimeException: failure, see logs for details.
@BindingAdapter on invalid element: void setSelectedItemPositionListener(android.support.v7.widget.AppCompatSpinner, android.databinding.InverseBindingListener)

1 Answers
Related