尝试显示对话框时出错
尝试显示带有时间选择器的对话框时遇到此问题,如果我使用从 getBaseContext()
返回的上下文初始化 TimePickerDialog
,而不是使用this
对当前活动的引用。 所以这段代码很好:
@Override
protected Dialog onCreateDialog( int id )
{
return new TimePickerDialog( this , mTimeSetListener, hr, min, false);
}
但是这段代码会抛出异常
protected Dialog onCreateDialog( int id )
{
return new TimePickerDialog( getBaseContext(), mTimeSetListener, hr, min, false);
}
如果我想显示一个Toast,那么我会使用
Toast.makeText( getBaseContext() , ...
它,这也有效。
我的问题是我本以为我希望对话框显示的上下文是baseContext,那么为什么Toast可以使用它,但对话框需要引用“this”,即当前的我认为它们的工作方式非常相似?
Had this problem when trying to display a Dialog with a time picker where an exception is thrown if I initialize the TimePickerDialog
with the context returned from getBaseContext()
as opposed to using a this
reference to the current activity.
So this code is fine:
@Override
protected Dialog onCreateDialog( int id )
{
return new TimePickerDialog( this , mTimeSetListener, hr, min, false);
}
but this code throws an exception
protected Dialog onCreateDialog( int id )
{
return new TimePickerDialog( getBaseContext(), mTimeSetListener, hr, min, false);
}
If I want to display a Toast then I would use
Toast.makeText( getBaseContext() , ...
and this also works.
My question is I would have thought the context I want the Dialog to display in would be the baseContext
so why does a Toast work using this but a Dialog needs a reference to "this" , i.e., the current activity as I would have thought they are both very similar in how they work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要使用
getBaseContext()
,除非您知道自己在做什么并且有非常具体且具体的使用原因。Toast
不需要它,Dialog
也不需要它。无论您使用什么Activity
,都是创建Toasts
和Dialogs
的完美Context
,所以只需使用<代码>这个。Do not use
getBaseContext()
unless you know what you are doing and have a very specific and concrete reason for using it.You do not need it for a
Toast
, and you do not need it for aDialog
. WhateverActivity
you are using for those is a perfectly goodContext
for creatingToasts
andDialogs
, so just usethis
.