通過Observable的方式去通知UI數(shù)據(jù)已經(jīng)改變了
- 我們的實體類要繼承BaseObservale類
- Getter上使用注解@Bindable
- 在Setter里調(diào)用方法notifyPropertyChanged
修改 javebean User.java
public class User extends BaseObservable {
String username;
String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
@Bindable
public String getUsername() {
return username;
}
@Bindable
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
notifyPropertyChanged( BR.username);
}
public void setPassword(String password) {
this.password = password;
notifyPropertyChanged(BR.password);
}
}
xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
type="com.lefeee.dbdemoapplication.bean.User"
name="user" />
<variable
type="com.lefeee.dbdemoapplication.MainActivity"
name = "click" />
</data>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.lefeee.dbdemoapplication.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.username}" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.password}"
android:clickable="true"
android:onClick="@{click.click}" />
</LinearLayout>
</layout>
activity中
public class MainActivity extends AppCompatActivity {
User user1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
user1 = new User("jack", "123456");
binding.setUser( user1 );
binding.setClick(this);
}
public void click( View view){
user1.setUsername("hero");
}
}