在数据绑定中的api调用后设置数据时,反向绑定中的类强制转换异常

时间:2019-07-15 13:03:32

标签: android android-fragments android-databinding 2-way-object-databinding

我的视图与xml和视图模型绑定,但是从自定义绑定适配器应用程序调用的InverseBindingAdapter在此时崩溃时,有什么建议吗?

这是我的视图模型

 @Bindable
fun getSpecialitieValue(): String? {
    return specialitiesValue

}

fun setSpecialitieValue(specialitieValue: String? ) {
    this.specialitiesValue = specialitieValue
    notifyPropertyChanged(BR.specialitieValue)
    //addspecialitiesdata(specialitiesValue)

}

这是我的具有绑定的xml文件

 <androidx.appcompat.widget.AppCompatSpinner
                        android:id="@+id/spspecialities"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="20dp"
                        android:layout_marginStart="24dp"
                        android:layout_marginLeft="24dp"
                        android:layout_marginTop="8dp"
                        android:layout_marginEnd="16dp"
                        android:layout_marginRight="16dp"
                        app:adapter="@{specialitiesAdapter}"
                        bind:specialitiesOpt="@={viewModel.specialitieValue}">

                </androidx.appcompat.widget.AppCompatSpinner>

这是我的自定义视图绑定

public class SpecialitieSpinnerBindingAdapter {

@BindingAdapter(value = {"bind:specialitiesOpt", "bind:specialitieOptAttrChanged"}, requireAll = false)
public static void setPmtOpt(final AppCompatSpinner spinner,
                             final String selectedPmtOpt,
                             final InverseBindingListener changeListener) {
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (changeListener!=null){
                changeListener.onChange();
            }
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            if (changeListener!=null){
                changeListener.onChange();
            }
        }
    });
    int selectionvalue=getIndexOfItem(spinner, selectedPmtOpt);
    if(selectionvalue!=-1){
        spinner.setSelection(selectionvalue);
    }

}
@InverseBindingAdapter(attribute = "bind:specialitiesOpt", event = "bind:specialitieOptAttrChanged")
public static String getPmtOpt(final AppCompatSpinner spinner) {
    return (String) spinner.getSelectedItem();
}

private static int getIndexOfItem(AppCompatSpinner spinner, String item){
    SpecialitiesSpinnerAdapter a = (SpecialitiesSpinnerAdapter) spinner.getAdapter();
    //Adapter a = spinner.getAdapter();
    if(a==null)
        return -1;
    for(int i=0; i<a.getCount(); i++){
        if((a.getItem(i)).equals(item)){
            return i;
        }
    }
    return 0;
    }
}

错误日志给出return (String) spinner.getSelectedItem();,该行有错误,这是类强制转换异常MYModel无法转换为字符串,所以我该怎么办?我究竟做错了什么?需要帮助。谢谢

0 个答案:

没有答案