无法获取应用上下文(未解决的引用)

问题描述 投票:1回答:2

我正在尝试获取应用程序的上下文,以打印Toast消息。我在Java中使用的功能如下:

Toast.makeText(getApplicationContext(), "Hey! I'm working", Toast.LENGTH_LONG).show();

但是现在,我需要在Kotlin中实现它,(我正在开始学习的语言)感到有点迷茫。我已经尝试了以下代码(在此post中给出),但由于我无法获取应用程序的上下文而无法正常工作。

Toast.makeText(this@CoreMainActivity, "Its toast!", Toast.LENGTH_LONG).show()

而且,我无法获得getApplicationContext()的上下文,因为它是用documentation编写的。

总结一下,我很高兴知道如何调用getApplicationContext(),并了解this@CoreMainActivity的确切功能(在帖子this@CoreMainActivity中)。 请注意,coreMainActivity是Java文件。

谢谢!

android kotlin
2个回答
0
投票

以下其中一项应起作用:

getContext()
getActivity()
this
CoreMainActivity.this

0
投票

根据您的代码

如果可行的话

Toast.makeText(getApplicationContext(), "Hey! I'm working", Toast.LENGTH_LONG).show();

然后它也应该起作用

Toast.makeText(applicationContext, "Its toast!", Toast.LENGTH_LONG).show()
© www.soinside.com 2019 - 2024. All rights reserved.