上一篇有提到,databinding的介紹,今天這篇要介紹的是,
假設model變更時,要如何讓view也跟著改變呢?
其實方法很簡單,android 有提供新的class BaseObservable
如下圖
public class User extends BaseObservable {
private String firstName;
private String lastName;
@Bindable
public String getFirstName() {
return firstName;
}
@Bindable
public String getLastName() {
return lastName;
}
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
notifyPropertyChanged(BR.firstName);
}
public void setLastName(String lastName) {
this.lastName = lastName;
notifyPropertyChanged(BR.lastName);
}
}
我們只需要在set之後,call notifyPropertyChanged就行了
TwowaydatabindingLayoutBinding binding;
User user;
private int i = 0;
@Overrideprotected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.twowaydatabinding_layout);
user = new User("Test", "User");
binding.setUser(user);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
user.setLastName("change " + i);
Toast.makeText(view.getContext(), " " + user.getLastName(), Toast.LENGTH_SHORT).show();
i++;
}
});
}
如上面的code所示,我在按鈕click的時候去改變user的lastName
然後edittext的lastname就會跟著改變
其實這種方法很像是adapter的notifydatasetChanged
不過目前這種方法只能用在 data change 通知 ui 改變
但是 ui 改變 -> data change這條路似乎還沒有看到任何的解法
希望在 android M正式release 的時候可以有 two-way binding的寫法出現.
沒有留言:
張貼留言