我正在尝试在运行时更新DialogFragment显示,根据某些条件将视图的可见性设置为可见或消失。
基本上,我在 DialogFragment 中膨胀我的布局,在我执行一些后台请求时显示进度条,并根据我的请求结果更新 DialogFragment 布局。
有时它可以工作,有时它不会相应地更新我的 UI,即使日志显示该方法被调用并且线程是主线程。知道为什么吗?
在对话片段中
@Override
public void showData(List<MyDataViewModel> data) {
Timber.d("Fragment Show data " + (Looper.myLooper() == Looper.getMainLooper()));
Timber.d("Fragment Show data " + this);
Timber.d("Fragment Show data " + data.size());
if (mConnectedContainer.getVisibility() != View.VISIBLE) {
mConnectedContainer.setVisibility(View.VISIBLE);
}
}
在活动中
@Override
public void showDialog() {
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance();
newFragment.show(ft, "dialog");
}
也尝试过这种方式
@Override
public void showDialog() {
// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance();
newFragment.show(getSupportFragmentManager(), "dialog");
}
经过一番调查,这个问题与我使用RxJava有关。我正在执行第一个用例,然后在下一个用例中执行另一个用例。
我将代码拆分为两个不同的对话框以使其更简单,并且只有一个用例更新 UI,不再有问题。