3. BaseObservable

通过Observable的方式去通知UI数据已经改变了

  1. 我们的实体类要继承BaseObservale类
  2. Getter上使用注解@Bindable
  3. 在Setter里调用方法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文件如下:




    
    



    

    






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");   
}

}

你可能感兴趣的:(3. BaseObservable)