我在使用Android数据绑定时遇到了一些麻烦。
我有一个这样的类。
class AppConfig private constructor() : BaseObservable() {
@Bindable
var title = ""
fun updateTitle(newTitle: String) {
title = newTitle
notifyPropertyChanged(BR.title)
}
......
}
当应用程序处于后台时,应用程序收到了一个更新推送,然后调用了updateTitle函数。然后我打开我的应用程序,我可以看到标题已经改变了。然后我再推送一次更新,标题没有变化。然后我按下home键,再把应用放到前面,标题就更新了。
我已经阅读了ViewDataBinding的源码。
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);
}
}
}
条件是... !state.isAtLeast(Lifecycle.State.STARTED)
第一次失败,而变量 mPendingRebind
被设为真。似乎只有当 mRebindRunnable
或 mFrameCallback
运转,可变 mPendingRebind
将再次被设置为false。所以UI永远不会刷新。
我见过这个问题 数据绑定--onActivityResult后XML不更新。. 我尝试使用SingleLiveEvent,并调用了 updateObserver.call()
在Activity的onResume中。没用。
我也试过用反射来设置 mPendingRebind
假的强行。可以用,但我觉得这个方法不好。我应该怎么做呢?
试试这个
var title = ""
@Bindable get() = title