在对话框外部按下时如何关闭 DialogFragment?
我正在使用 DialogFragment ,虽然我已成功设置图像以在按下时关闭(即关闭)对话框,但我很难找到当用户单击任意位置时关闭对话框的方法在它之外,就像它在普通对话框中一样。我以为会有某种调用
dialogFragment.setCanceledOnTouchOutside(true);
,但我在文档中没有看到这一点。
这对于 DialogFragment
是否可行?或者我找错地方了?我尝试拦截“父”活动中的触摸事件,但除了没有收到任何触摸事件之外,这对我来说似乎不正确。
I am using a DialogFragment
, and while I have successfully set an image to close (i.e. dismiss) the dialog when pressed, I am having a hard time finding the way to dismiss the dialog when the user clicks anywhere outside it, just as it works with normal dialogs. I thought there would be some sort of
dialogFragment.setCanceledOnTouchOutside(true);
call, but I don't see that in the documentation.
Is this possible with DialogFragment
at all? Or am I looking in the wrong places? I tried intercepting touch events in the 'parent' activity but apart from not getting any touch event, it didn't seem right to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
这里有很多答案,但是当对话框打开时应用程序崩溃。
在
onCreateView
内写入getDialog().setCanceledOnTouchOutside(true);
不起作用,并使我的应用程序崩溃。(我使用
AppCompatActivity
作为我的 BaseActivity,使用android.app.DialogFragment
作为我的 Fragment)。有效的是以下两行之一:
或者
在
onActivityCreated
内,例如不可以使用的内容:
引发以下错误
在
onCreateView
中编写代码会使应用程序崩溃!如果您发现有问题,请更新答案。
Lot of answers here but, the app crash when dialog opens.
Writing
getDialog().setCanceledOnTouchOutside(true);
insideonCreateView
did not work and crashed my app.(I am using
AppCompatActivity
as my BaseActivity andandroid.app.DialogFragment
as my Fragment).What works is either of the two following lines:
OR
inside
onActivityCreated
likeWhat not to use:
throws following error
And writing the code in
onCreateView
crashes the App!Please update the answer if you find something wrong.
如果您想在点击
DialogFragment
外部时执行某些逻辑,只需重写 onCancel 方法即可。If you want to execute some logic when clicking outside of a
DialogFragment
, just override the onCancel method.这对于 Java 来说效果很好:
This works fine for Java:
我建议仅在尝试上述解决方案后才使用我的解决方案。我在此处描述了我的解决方案。简而言之,我正在检查 DialogFragment.getView() 的触摸边界。当触摸点位于 DialogFragment 之外时,我将关闭该对话框。
I would recommend to use my solution only after trying out above solutions. I have described my solution here. Just to brief, I am checking touch bounds of DialogFragment.getView(). When touch points are outside DialogFragment, I am dismissing the Dialog.
为我工作
我的代码
Worked for me
My Code
必须在 onCreateView 中调用(正如 Apurv Gupta 指出的那样)。
Must be called in
onCreateView
(as Apurv Gupta pointed out).