在 kotlin 中访问伴随对象中的应用程序上下文 [英] Access application context in companion object in kotlin
本文介绍了在 kotlin 中访问伴随对象中的应用程序上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们如何在 Android kotlin 中访问伴随对象内的应用程序上下文?我在抽象类中有一个伴随对象,我想访问上下文以读取共享首选项,但我无法获取上下文.
How can we access application context inside companion object in Android kotlin? I have a companion object inside an abstract class and I want to access context to read Shared Preferences, but I'm not able to get the context.
更新:我正在一个 Android 库中使用这些东西,而且我正在使用的类是抽象的
UPDATE: I'm working with this stuff in an Android library and also the class that I'm working in is abstract
推荐答案
实际上我在一个 Android 库中工作并且该类是抽象的,所以不能采用已经建议的解决方案.但是,我找到了方法.
Actually I'm working inside an Android library and the class is abstract, so can't go with the already suggested solutions. However, I found way to do that.
- 在伴随对象中创建一个
lateinit
上下文字段.
- Creat a
lateinit
Context field inside companion object.
abstract class MyClass {
companion object {
private lateinit var context: Context
fun setContext(con: Context) {
context=con
}
}
}
- 然后在应用启动后进行设置
public class WelcomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
MyClass.Companion.setContext(this);
}
}
这篇关于在 kotlin 中访问伴随对象中的应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文