我在编辑活动中使用双向数据绑定,我试图避免使用电子设备,我需要知道该活动的数据何时发生变化。我已经为EditText创建了一个完美的TextWatcher。现在我想用Spinner做同样的事情。所以我创建了一个SpinnerWatcher类,在我的模型视图(POJO)和我的布局中引用它。一切都编译并运行但我没有得到预期的结果。这条线
hasDataChanged = true;
永远不会被执行。我想在布局文件中指定setOnItemSelectedListener,在ViewModel中指定逻辑,而不是在活动中。
这是我的SpinnerWatcher类:
public abstract class MySpinnerWatcher implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public abstract void onItemSelected(AdapterView newValue);
}
这是我的视图模型:
public class Diver extends BaseObservable {
...
@Bindable
public AdapterView.OnItemSelectedListener getOnSpinnerChanged() {
return new MySpinnerWatcher() {
@Override
public void onItemSelected(AdapterView newValue) {
// This never gets executed
hasDataChanged = true;
}
};
}
}
这是我的布局:
<android.support.v7.widget.AppCompatSpinner
android:id="@+id/spinnerGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/gender_arrays"
android:prompt="@string/gender_prompt"
app:setOnItemSelectedListener="@{diverdb.getOnSpinnerChanged}"
style="@style/Widget.AppCompat.Spinner.Underlined"/>
在Spinner中更改值时如何触发onItemSelected()?
答案 0 :(得分:1)
我能够修复我的代码。
这是我的Spinner观察者课程:
public class MySpinnerWatcher implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
这是我的View模型:
@Bindable
public AdapterView.OnItemSelectedListener getOnSpinnerChangedDiveType() {
return new MySpinnerWatcher() {
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
super.onItemSelected(parent, v, position, id);
// The Hint is in the list at item 0
if (position != 0 && position + 1 != mDiveTypePosition){
mHasDataChanged = true;
// The Hint is in the list at item 0
DiveType diveType = (DiveType) parent.getAdapter().getItem(position + 1);
mDiveType = diveType.getDiveType();
}
}
};
}
这是我的布局:
<fr.ganfra.materialspinner.MaterialSpinner
android:id="@+id/spinnerDiveType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:selectedItemPosition="@={dive.diveTypePosition}"
app:ms_floatingLabelColor="@color/blue"
app:ms_multiline="true"
app:ms_enableFloatingLabel="true"
app:ms_enableErrorLabel="false"
app:ms_floatingLabelText="Dive Type"
app:ms_hint="Dive Type"
app:setOnItemSelectedListener="@{dive.getOnSpinnerChangedDiveType}"
app:adapter="@{dive.AdapterDiveType}"
/>