3
我希望用戶在EditText
中輸入其名稱並在TextView
內顯示Hello {name}
。當我將TextView
的文本設置爲可觀察屬性(user.firstName
)時,文本會更新。即使我將文本設置爲模型的toString()
方法,它仍然可以正常工作。但是,如果我改用viewModel.hello
,則文本不會更新。我錯過了什麼?Android:數據綁定文本未更新
型號:
public class User extends BaseObservable {
public String firstName;
public String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Bindable
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
notifyPropertyChanged(BR.firstName);
}
@Bindable
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
notifyPropertyChanged(BR.lastName);
}
@Override
public String toString() {
return getFirstName() + " " + getLastName();
}
}
視圖模型:
public class ViewModel {
public User user;
public ViewModel() {
user = new User("", "");
}
public String hello() {
return "Hello " + user.toString();
}
public TextWatcher userNameTextWatcher() {
return new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.toString().length() == 0) {
user.setFirstName("");
user.setLastName("");
user.notifyChange();
return;
}
String[] name = editable.toString().split(" ");
if (name.length == 1) {
user.setFirstName(name[0]);
user.setLastName("");
user.notifyChange();
return;
}
String firstName = name[0] + " ";
for (int i = 0; i < name.length - 2; i++) {
firstName = firstName + " " + name[i] + " ";
}
user.setFirstName(firstName);
user.setLastName(name[name.length - 1]);
user.notifyChange();
}
};
}
}
佈局:
<data>
<variable
name="viewModel"
type=".ViewModel"/>
</data>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="@{viewModel.hello}"/>
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView"
android:layout_marginTop="8dp"
app:addEditTextWatcher="@{viewModel.userNameTextWatcher}"/>
嗨,你可以請看看我的問題https://stackoverflow.com/q/45143721/5214893 –