我想将此自定义微调器与数据绑定一起使用,以将条目与我的列表绑定:https://github.com/miteshpithadiya/SearchableSpinner
一切都适用于标准微调器,示例xml布局:
<android.support.v7.widget.AppCompatSpinner
android:id="@+id/add_event_internal_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="@dimen/default_margin"
android:entries="@{event.internalCategoryNames}"
android:prompt="@string/spinner_category_title"
android:selectedItemPosition="@={event.selectedInternalCategoryPosition}"
android:visibility="@{event.editable?View.VISIBLE:View.GONE}"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView6"/>
但是,如果我尝试使用可搜索的微调器控件而不是标准微调器,我会得到一个例外:
java.lang.ClassCastException: android.databinding.adapters.ObservableListAdapter无法强制转换为 android.widget.ArrayAdapter
当控件尝试设置适配器时,抛出异常,代码:
@Override
public void setAdapter(SpinnerAdapter adapter)
{
if (!_isFromInit)
{
_arrayAdapter = (ArrayAdapter) adapter; //--EXCEPTION
if (!TextUtils.isEmpty(_strHintText) && !_isDirty)
{
ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
.simple_list_item_1, new String[]{_strHintText});
super.setAdapter(arrayAdapter);
}
else
{
super.setAdapter(adapter);
}
}
else
{
_isFromInit = false;
super.setAdapter(adapter);
}
}
ObservableListAdapter
是私有的,因此无法使用。你知道什么是错的吗? SearchableSpinner
扩展了Spinner
课程:https://github.com/miteshpithadiya/SearchableSpinner/blob/master/searchablespinnerlibrary/src/main/java/com/toptoche/searchablespinnerlibrary/SearchableSpinner.java
答案 0 :(得分:0)
您会遇到该异常,因为用于android:entries
的数据绑定系统标准绑定适配器使用并设置了ObservableListAdapter
。
在AbsSpinnerBindingAdapter
中(与androidx或android无关):
@BindingAdapter({"android:entries"})
public static <T> void setEntries(AbsSpinner view, List<T> entries) {
if (entries != null) {
SpinnerAdapter oldAdapter = view.getAdapter();
if (oldAdapter instanceof ObservableListAdapter) {
((ObservableListAdapter) oldAdapter).setList(entries);
} else {
view.setAdapter(new ObservableListAdapter<T>(view.getContext(), entries,
android.R.layout.simple_spinner_item,
android.R.layout.simple_spinner_dropdown_item, 0));
}
} else {
view.setAdapter(null);
}
}
因此可以使用AppCompatSpinner
(也可以使用Spinner
),但是您使用的SearchableSpinner
希望它是ArrayAdapter
。
解决方案
您必须声明自己的绑定适配器,即自定义设置器,该适配器使用ArrayAdapter
。您可以为android:entries
属性提供自己的属性(数据绑定系统将使用您的属性而不是标准的属性),或者发明一个新的属性名称并在XML中使用它(例如bind:entries
)。
如果您不知道如何,请看看here。