这个问题的原因是,将新值分配给模型时,数据绑定框架不知道需要更新UI。因此,我们需要调用notifyPropertyChanged()或notifyChange()方法来通知框架更新UI。
以下是一个简单的示例,演示如何为模型分配新值并更新UI:
在布局文件中,我们将绑定模型的属性,并在文本视图中显示它:
在一个活动中,我们创建一个模型实例并将其设置为数据绑定的变量,并在按钮的单击事件中更改模型的名称属性:
public class MainActivity extends AppCompatActivity {
private User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
// Create a new user
user = new User("John");
binding.setUser(user);
// Set a click listener for a button
binding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Change the name property of the user
user.setName("Jane");
// Notify the data binding framework that the property has changed
binding.notifyPropertyChanged(BR.user);
}
});
}
}
当用户单击按钮时,模型的“名称”属性将更改为“Jane”,并且应更新UI以反映更改。
在单击事件处理程序中,我们使用notifyPropertyChanged()方法来通知数据绑定框架,模型的属性已更改。我们还传递了BR.user,这是我们在数据绑定布局中为模型所定义的变量的ID。
通过这样做,我们可以确