我如何从不同类别中使用的主动行为获得上下文,而无需传递
我有一个定制班级列表和一个函数,可以在他们自己的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论