-2

When we use MutableLiveData in ViewModel when we use it in XML, Android Studio does not offer it to us?

public class LoginViewModel extend ViewModel {

    public MutableLiveData<UserEntity> userEntity;

    public UserEntity userEntity1;

}

public UserEntity userEntity1;

enter image description here

userEntity1 is Work but userEntity is not work.

How to resolve this problem?

Update:

The Android Studio 3.4.2 is fixed this bug.

Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98

1 Answers1

1

You need to have public getters in your view model to access the fields from the 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();
    }
}

Then you can access fields in the xml like this:

Option 1:

android:text="@{userEntityViewModel.user.name}"

Option 2:

android:text="@{userEntityViewModel.userName}"

Hope it helps.

holparb
  • 157
  • 3
  • 13
  • In this approach, I have a doubt that it doesn't update any value in the model itself because it doesn't have any setter method. – Bhavin Shah Mar 28 '19 at 13:16