【发布时间】:2020-04-02 19:17:50
【问题描述】:
我想将上下文传递给我的自定义类意味着某些功能的 Utils。我想创建我的自定义 Toast 来显示我的消息。为此我需要上下文但我的 toast 函数是静态的并且不能使用它,因为我们可以获得非静态函数中的静态变量。如何将上下文传递给 Utils 类并在 Utils 类的静态函数中使用上下文? 我知道我可以在 show 而不是 Utils 类中获取上下文,但我想在 Utils 类中获取上下文并将其用于其他功能。 在我的代码中,上下文在显示功能中无法访问
class Utils(var context:Context){
companion object{
fun show(){
Toast.makeText(context,message,Toast.LENGTH_SHORT).show()
}
}
}
【问题讨论】:
标签: kotlin constructor static android-context companion-object