在Kotlin中的伴随对象中访问应用程序上下文 [英] Access application context in companion object in kotlin

查看:226
本文介绍了在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.

  1. 在伴随对象内创建一个lateinit上下文字段.
  1. Creat a lateinit Context field inside companion object.

abstract class MyClass {

    companion object {

        private lateinit var context: Context

        fun setContext(con: Context) {
            context=con
        }
    }
}

  1. 然后在应用启动后进行设置

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆