Android:如何覆盖AlertDialog中的onBackPressed()?
我有一个 AlertDialog dlgDetails
,它是从另一个 AlertDialog dlgMenu
显示的。如果用户按下 dlgDetails 中的后退按钮,我希望能够再次显示 dlgMenu,并且如果用户按下对话框之外的按钮,则只需退出对话框。
我认为最好的方法是重写 dlgDetails 的 onBackPressed ,但我不确定如何做到这一点,因为必须使用生成器间接创建 AlertDialogs 。
我正在尝试创建一个派生的 AlertDialog (public class AlertDialogDetails extends AlertDialog { ...}
),但我想我还必须在该类中扩展 AlertDialog.Builder
才能返回AlertDialogDetails,但是有没有更简单的方法?如果没有,您将如何覆盖构建器?
I have an AlertDialog dlgDetails
which is shown from another AlertDialog dlgMenu
. I would like to be able to show dlgMenu again if the user presses the back button in dlgDetails and simply exit the dialog if he presses outside the dialog.
I think the best way to do this is to override onBackPressed
for dlgDetails, but I am not sure how to do that since AlertDialogs must be created indirectly using the Builder.
I am trying to create a derived AlertDialog (public class AlertDialogDetails extends AlertDialog { ...}
) but then I guess I must also extend AlertDialog.Builder
in that class to return an AlertDialogDetails, but isn't there a simpler way? And if not, how would you go about overriding the Builder?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我最终在对话框中添加了一个按键侦听器来侦听“后退”键。
不像重写 onBackPressed() 那样优雅,但它可以工作。
下面是代码:
有关 Kotlin 中的答案,请参见此处:当 Alertdialog 的 setcancelable 为 false 时,无法在backpressed 上工作
I finally added a key listener to my dialog to listen to the Back key.
Not as elegant as overriding
onBackPressed()
but it works.Here is the code:
For answer in Kotlin see here:Not working onbackpressed when setcancelable of alertdialog is false
找到了一个更短的解决方案:)试试这个:
Found a shorter solution :) try this:
这会处理“后退”按钮和对话框外部的单击:
dialog.cancel()
是关键:使用dialog.dismiss()
这只会处理对话框外部的单击对话框,如上面回答。This handles both the BACK button and the click OUTSIDE the dialog:
dialog.cancel()
is the key: withdialog.dismiss()
this would handle only the click outside of the dialog, as answered above.我在 java 类中创建了一个新函数,并从对话框生成器的 onClick 方法调用了该函数。
I created a new function within the java class and made a call to that function from the onClick method of the dialog Builder.
这是 C# 的实际解决方案,基于 Pooks 的答案:
首先,我们必须创建一个新类来处理事件:
我们需要一个操作来接收事件:
现在,我们可以设置此事件:
Here is an actual solution for C#, based on the answer from Pooks:
First, we have to create a new class for handling the event:
And we need an action to receive the event:
Now, we can set up this event: