尝试显示对话框时出错

发布于 2024-12-06 15:21:31 字数 690 浏览 2 评论 0原文

尝试显示带有时间选择器的对话框时遇到此问题,如果我使用从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隔岸观火 2024-12-13 15:21:31

不要使用getBaseContext(),除非您知道自己在做什么并且有非常具体且具体的使用原因。

Toast 不需要它,Dialog 也不需要它。无论您使用什么Activity,都是创建ToastsDialogs的完美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 a Dialog. Whatever Activity you are using for those is a perfectly good Context for creating Toasts and Dialogs, so just use this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文