我想用Android數據綁定使用MVVM模式。 我有一個edittext和一個textview,當我通過帶有LocationType模型對象的observablefield綁定到模型來輸入edittext字段時應該顯示相同的文本。Android雙向數據綁定,textview不更新
從測試這兩個字段都設置爲「你好」,當我啓動應用程序,如預期的那樣。 但是,當我輸入edittextfield的時候,textview並沒有更新,甚至很難通過調試來看到模型對象被正確更新。
當我使用:使用模型,只是設置一些文本和更新使用該領域的XML
observablefield<String>
下降。它按預期工作。
型號:
public class LocationType {
private String locationType;
public String getLocationType() {
return locationType;
}
public void setLocationType(String locationType) {
this.locationType = locationType;
}
}
MODELVIEW:
public class LocationTypeViewModel extends BaseObservable {
@Bindable
private ObservableField<LocationType> locationTypeObservableField = new ObservableField<>();
private Context context;
LocationType locationType;
public LocationTypeViewModel(Context context) {
this.context = context;
locationType = new LocationType();
locationType.setLocationType("Hello");
locationTypeObservableField.set(locationType);
}
public ObservableField<LocationType> getLocationTypeObservableField() {
Log.d("CALLED GET", locationType.getLocationType());
return locationTypeObservableField;
}
}
XML:
<layout xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="android.view.View"/>
<variable
name="viewModel"
type="fragment.LocationType.viewmodel.LocationTypeViewModel"/>
</data>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="@{viewModel.locationTypeObservableField.locationType}"
android:id="@+id/edittext1"/>
<TextView
android:layout_below="@+id/edittext1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="@{viewModel.locationTypeObservableField.locationType}"
android:id="@+id/text"
/>
</RelativeLayout>
</layout>
謝謝!我有@ =之前不知道它是如何迷路的。但是,我怎樣才能將模型作爲POJO? – Morti
您可以讓LocationType對象擴展BaseObservable,然後當某個字段發生變化時應該遵守,您需要從BR生成的類中通知正確的ID。查看文檔中的Observable對象:https://developer.android.com/topic/libraries/data-binding/index.html。那裏有一個相對的例子。 –
我明白了,是爲MVVM模式設計時做的事嗎?在大多數例子中,Viewmodel是擴展BaseObservable的一個例子。 – Morti