在ObservableField
的{{1}}内部更新onActivityResult(..)
,但不将该值反映到activity
。如果我调用executePendingBindings(),它将起作用。但是问题是,XML
有很多,对于每个变量,我都需要调用ObservableField
。
有人知道如何解决这个问题吗?
答案 0 :(得分:3)
在ViewDataBinding.java
文件中,有一种请求重新绑定的方法
protected void requestRebind() {
if (mContainingBinding != null) {
mContainingBinding.requestRebind();
} else {
synchronized (this) {
if (mPendingRebind) {
return;
}
mPendingRebind = true;
}
if (mLifecycleOwner != null) {
Lifecycle.State state = mLifecycleOwner.getLifecycle().getCurrentState();
if (!state.isAtLeast(Lifecycle.State.STARTED)) {
return; // wait until lifecycle owner is started
}
}
if (USE_CHOREOGRAPHER) {
mChoreographer.postFrameCallback(mFrameCallback);
} else {
mUIThreadHandler.post(mRebindRunnable);
}
}
}
当控件进入该方法时,mPendingRebind
将为false,并且此方法将变为true。 mChoreographer.postFrameCallback(mFrameCallback);
将再次将该变量设置为false,以便其他绑定将更新视图。
问题是!state.isAtLeast(Lifecycle.State.STARTED)
状态。由于ObservableField已从onActivityResult(..)
更新,因此当前状态将为Lifecycle.State.CREATED
,因此该条件将失败并返回该方法而无需调用mChoreographer.postFrameCallback(mFrameCallback);
,并且mPendingRebind
将为true。因此,剩余的绑定不会更新。
因此解决方案是调用SingleLiveEvent
并观察该变量。收到该回调后,我们必须更新ObservableField()
例如:
val updateObserver = SingleLiveEvent<Unit>()
然后观察该事件
updateObserver.observe(this, Observer {
//update ObservableField
})
从onActivityResult调用该事件
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 111 && resultCode == Activity.RESULT_OK) {
updateObserver.call()
}
}
答案 1 :(得分:0)
如果您不想创建SingleLiveEvent
,而是希望将回调代码保留在onActivityResult
中,并且您有一个扩展所有活动的基础活动,则可以添加一个{{1 }}基本活动的方法:
scheduleUpdateAfterOnActivityResult
然后
// When onActivityResult is run, the activity is still in Lifecycle.State.CREATED and
// bindings will not fire. Schedule the update by creating a new MutableLiveData,
// which will fire observers when activity lifecycle is active.
// See also https://stackoverflow.com/questions/53104670/data-binding-xml-not-updating-after-onactivityresult/53107092
public <T> void scheduleUpdateAfterOnActivityResult(T data, Observer<T> observer) {
final MutableLiveData<T> liveData = new MutableLiveData<>();
liveData.observe(this, new Observer<T>() {
@Override
public void onChanged(@Nullable final T v) {
observer.onChanged(v);
liveData.removeObserver(this);
}
});
liveData.postValue(data);
}
致电onActivityResult
:
scheduleUpdateAfterOnActivityResult()