您需要在视图模型中有公共 getter 才能从 xml 访问字段。
public class LoginViewModel extends ViewModel {
private MutableLiveData<UserEntity> userEntity;
//Mandatory zero parameter constructor, if non zero parameter constructor is necessary, a factory needs to be created for the ViewModel
public LoginViewModel() {}
//Option 1: Public getter for the userEntity object
public MutableLiveData<UserEntity> getUserEntity() {
return userEntity;
}
//Option 2: Alternatively a separate getter can be used for different fields of the model class
public String getUserName() {
return userEntity.getValue().getName();
}
}
然后您可以像这样访问 xml 中的字段:
选项1:
android:text="@{userEntityViewModel.user.name}"
选项 2:
android:text="@{userEntityViewModel.userName}"
希望能帮助到你。