你们中的任何人在将片段添加到片段管理器后都没有遇到过片段吗?当我们试图隐藏它时,它会停留在屏幕上。
从 fragment:onActivityCreated 我们显示对话框:
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
// Push the progress dialog
String text = getActivity().getString(R.string.httpLoadingData);
((BaseFragmentActivity) getActivity()).showHttpWaitingDialog(text);
...
}
稍后从新线程中的同一片段中我们隐藏对话框:
private void prepareInitialWebViewData() {
initialFragmentWebDataLoadingThread = new Thread(new Runnable() {
@Override
public void run() {
updateDataAndView();
BaseFragmentActivity activity = (BaseFragmentActivity) getActivity();
BaseFragmentActivity activity = (BaseFragmentActivity) getActivity();
if (activity != null)
{
activity.hideHttpWaitingDialog();
}
// We don't need to keep this handle any longer since we've done
// the work
initialFragmentWebDataLoadingThread = null;
}
});
initialFragmentWebDataLoadingThread.start();
}
这是在我们的 BaseFragmentActivity 中找到的用于显示和隐藏的代码。请注意,可能会多次调用 showdialog,因此我们保留一个 refcount。
首先是show函数:
public void showHttpWaitingDialog(CharSequence title)
{
synchronized (mRefCount)
{
mRefCount++;
Log.w("showhideHttpWaitingDialog", "++mRefCount:" + mRefCount + ", Title:" + title);
FragmentManager fm = getSupportFragmentManager();
if (fm != null)
{
Fragment frag = fm.findFragmentByTag("httpWaitDialog");
if (frag == null)
{
WaitingOnHttpFragmentDialog dialog = WaitingOnHttpFragmentDialog.newInstance(title);
fm.beginTransaction().add(dialog, "httpWaitDialog").commit();
}
}
else
Log.w("showhideHttpWaitingDialog", "fragman == null");
}
}
然后隐藏功能:
public void hideHttpWaitingDialog()
{
synchronized (mRefCount)
{
Log.w("showhideHttpWaitingDialog", "--mRefCount:" + mRefCount);
if (mRefCount < 0)
{
Log.w("showhideHttpWaitingDialog", "Why are you trying to hide something that doesn't exists?");
mRefCount = 0;
}
else
{
if (mRefCount == 0)
{
FragmentManager fragman = getSupportFragmentManager();
if (fragman != null)
{
Fragment frag = fragman.findFragmentByTag("httpWaitDialog");
if (frag != null)
{
fragman.beginTransaction().remove(frag).commit();
Log.w("showhideHttpWaitingDialog", "dismissed normally");
}
else
Log.w("showhideHttpWaitingDialog", "httpWaitDialog not found!");
}
}
}
}
}