Spinner
doesn't have an attribute android:entries
so that isn't how to bind a value to a Spinner. I was wrong about that, even though I implemented it!
The entries attribute takes an array of CharSequence
. If you want it to take an arbitrary collection:
@BindingAdapter({"android:entries"})
public static void setEntries(AbsSpinner view, List<String> entries) {
if (entries != null) {
SpinnerAdapter oldAdapter = view.getAdapter();
boolean changed = true;
if (oldAdapter != null && oldAdapter.getCount() == entries.size()) {
changed = false;
for (int i = 0; i < entries.size(); i++) {
if (!entries.get(i).equals(oldAdapter.getItem(i))) {
changed = true;
break;
}
}
}
if (changed) {
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(view.getContext(),
android.R.layout.simple_spinner_item,
entries.toArray(new String[entries.size()]);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
view.setAdapter(adapter);
}
} else {
view.setAdapter(null);
}
}
You should probably use an ObservableList
instead of List
and add a listener that updates your ArrayAdapter every time the values change.
Because it is an AdapterView
, you'd typically use the setAdapter()
method. Therefore, you can use the automatically generated attribute app:adapter="@{myAdapter}"
to use the setAdapter()
method.
If you want to use a custom attribute like "entries", you can create one using a BindingAdapter
. Inside a class in your application -- doesn't matter which class, but by convention these are grouped by the target View type:
public class SpinnerAdapter {
@BindingAdapter("entries")
public static void setEntries(Spinner view, final List<String> values) {
SpinnerAdapter spinnerAdapter = new SpinnerAdapter() {
// Use values to implement the SpinnerAdapter
}
view.setAdapter(spinnerAdapter);
}
}
If you want to use a custom collection, replace List<String> with whatever your custom collection type is. If you want it to be observable, Adapter supports data change notifications, so make sure to add a listener to whatever list you provide (e.g. ObservableList
) and notify the adapter change.