フラグメントマネージャーに追加した後、フラグメントが見つからないという経験をしたことがありますか?非表示にしようとすると、画面に表示されたままになります。
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();
}
これは、showとhideの両方の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!");
}
}
}
}
}