android LiveData的值没有变化

时间:2018-04-12 05:07:37

标签: android android-livedata android-viewmodel

我做过像文档here,但实时数据的价值并没有改变。请告诉我我做错了什么。 MainActivity

公共类MainActivity扩展了AppCompatActivity {

private NameViewModel mModel;
private ActivityMainBinding binding;
int index = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    binding.button.setOnClickListener((v) -> {
        mModel.getCurrentName().setValue("Test");
    });

    mModel = ViewModelProviders.of(this).get(NameViewModel.class);

    final Observer<String> nameObserver = (text) -> {
        binding.textInputLayout.getEditText().setText(text);
    };

    mModel.getCurrentName().observe(this, nameObserver);

}
}

NameViewModel.java

public class NameViewModel extends ViewModel {
private MutableLiveData<String> mCurrentName;

public MutableLiveData<String> getCurrentName() {
    if (mCurrentName == null) {
        return new MutableLiveData<>();
    }
    return mCurrentName;
}
}

1 个答案:

答案 0 :(得分:1)

这是因为,您的逻辑每次都会返回mCurrentName的新实例。请使用以下功能。

public class NameViewModel extends ViewModel {
    private MutableLiveData<String> mCurrentName;

    public MutableLiveData<String> getCurrentName() {
        // Ensure there is only 1 instance of mCurrentName
        if (mCurrentName == null) {
            mCurrentName = new MutableLiveData<>();
        }
        return mCurrentName;
    }
}

更好更安全的方法(减少犯错的可能性)是在构造函数中初始化mCurrentName,并将其标记为final。

public class NameViewModel extends ViewModel {
    private final MutableLiveData<String> mCurrentName;

    public NameViewModel() {
        mCurrentName = new MutableLiveData<>();
    }

    public MutableLiveData<String> getCurrentName() {
        return mCurrentName;
    }
}