【发布时间】:2018-03-19 13:47:08
【问题描述】:
示例视图模型:
public class NameViewModel extends ViewModel {
// Create a LiveData with a String
private MutableLiveData<String> mCurrentName;
public MutableLiveData<String> getCurrentName() {
if (mCurrentName == null) {
mCurrentName = new MutableLiveData<>();
}
return mCurrentName;
}
}
主要活动:
mModel = ViewModelProviders.of(this).get(NameViewModel.class);
// Create the observer which updates the UI.
final Observer<String> nameObserver = textView::setText;
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.getCurrentName().observe(this, nameObserver);
我想在第二个活动中调用mModel.getCurrentName().setValue(anotherName); 并让 MainActivity 接收更改。这可能吗?
【问题讨论】:
-
“正确”的答案是“如果你想在它们之间共享数据,它们不应该是不同的活动,而是应该交换片段”。
-
@EpicPandaForce 也许,但这不是 AndroidStudio 主/详细模板的工作方式,也不是 Android 架构蓝图
-
@Mark 那是 Android 架构蓝图和模板的缺陷。
标签: java android android-livedata