android:如何检查dialogfragment是否显示 [英] android: how do I check if dialogfragment is showing
问题描述
我使用以下命令启动对话框片段
I launch my dialog fragment using
FragmentTransaction ft =
getFragmentManager().beginTransaction();
MyDialogFragment dialog = new MyDialogFragment()
dialog.show(ft, "dialog");
然后了解一下
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
但是一旦得到prev
,如何检查它是否显示?
but once I get prev
, how do I check if it is showing?
背景故事
我的问题是我的循环代码不断地启动对话框.但是,如果对话框已经显示,我不希望它再次启动. 这回故事只是为了背景.我寻求的答案不是:将其移出循环."
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."
推荐答案
简单检查其是否为空
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.
或者,您可以检查片段prev
当前与之关联的活动,但是,请确保在之后询问是否不为null或得到NullPointerException.像这样:
Alternatively, you could check the activity the fragment prev
is currently associated with, however, make sure you ask that after you make sure it's not null or you'll get a NullPointerException. Like this:
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"
这篇关于android:如何检查dialogfragment是否显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!