我如何从不同类别中使用的主动行为获得上下文,而无需传递

发布于 2025-02-07 18:27:13 字数 562 浏览 1 评论 0原文

我有一个定制班级列表和一个函数,可以在他们自己的kotlin文件中返回此列表。该函数仅是从MainActivity调用的,但是由于它不在同一文件中,因此在构建列表时无法通过上下文。

在自定义类定义中,我想在共享的偏好中访问变量,但是要这样做,我需要一个上下文,这将是MARATIVITY。因此,我的问题是如何从其他地方获取主要活性上下文,还是有另一种访问共享偏好的方法?

自定义类包含:

open class ListItems(
    open val title: String,
    ...
)

class GameName(
    override val title: String,
    ...
) : ListItems(title, active) {
    init {
        val context: Context = MainActivity::class
        val savedData = context.getSharedPreferences("CompletedGames", Context.MODE_PRIVATE)
        ...
    }
}

I have a list of CustomClass and a function which returns this list in their own kotlin file. The function is only ever called from MainActivity but since it is not in the same file I cannot pass context when building the list.

In the custom class definition I want to access a variable in shared preferences, but to do this I need a context, which would be MainActivity. So my question is how do I grab MainActivities context from elsewhere, or is there another way to access shared preferences?

The custom class contains:

open class ListItems(
    open val title: String,
    ...
)

class GameName(
    override val title: String,
    ...
) : ListItems(title, active) {
    init {
        val context: Context = MainActivity::class
        val savedData = context.getSharedPreferences("CompletedGames", Context.MODE_PRIVATE)
        ...
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文