android:我如何检查dialogfragment是否显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21352571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
android: how do I check if dialogfragment is showing
提问by learner
I launch my dialog fragment using
我使用启动我的对话框片段
FragmentTransaction ft =
getFragmentManager().beginTransaction();
MyDialogFragment dialog = new MyDialogFragment()
dialog.show(ft, "dialog");
then to get a handle on it I do
然后为了处理它,我做
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
but once I get prev, how do I check if it is showing?
但是一旦我得到prev,我如何检查它是否显示?
Back Story
背景故事
My problem is that my looping code keeps launching the dialog again and again. But if the dialog is already showing, I don't want it to launch again. This back story is just for context. The answer I seek is not: "move it out of the loop."
我的问题是我的循环代码不断地启动对话框。但如果对话框已经显示,我不希望它再次启动。这个背景故事只是为了上下文。我寻求的答案不是:“将其移出循环”。
采纳答案by nstosic
simply check if it's null
只需检查它是否为空
if(prev == null)
//There is no active fragment with tag "dialog"
else
//There is an active fragment with tag "dialog" and "prev" variable holds a reference to it.
Alternatively, you could check the activity the fragment previs currently associated with, however, make sure you ask that afteryou make sure it's not null or you'll get a NullPointerException. Like this:
或者,您可以检查片段prev当前关联的活动,但是,请确保在确定它不为空后询问,否则您将收到 NullPointerException。像这样:
if(prev == null)
//There is no active fragment with tag "dialog"
else
if(prev.getActivity() != this) //additional check
//There is a fragment with tag "dialog", but it is not active (shown) which means it was found on device's back stack.
else
//There is an active fragment with tag "dialog"
回答by j2emanue
if (dialogFragment != null
&& dialogFragment.getDialog() != null
&& dialogFragment.getDialog().isShowing()
&& !dialogFragment.isRemoving()) {
//dialog is showing so do something
} else {
//dialog is not showing
}
回答by John Leehey
I added this to be inside my custom dialog fragment, so I don't have to worry about any logic on the outside. Override the show()and onDismiss()methods, with a boolean shownfield:
我将此添加到我的自定义对话框片段中,因此我不必担心外部的任何逻辑。用一个字段覆盖show()和onDismiss()方法boolean shown:
private static boolean shown = false;
@Override
public void show(FragmentManager manager, String tag) {
if (shown) return;
super.show(manager, tag);
shown = true;
}
@Override
public void onDismiss(DialogInterface dialog) {
shown = false;
super.onDismiss(dialog);
}
If you want to check whether it is shown or not, you can create a getter for the shownboolean.
如果要检查它是否显示,可以为shown布尔值创建一个 getter 。

