gpt4 book ai didi

android - 如何在 Kotlin Room Entity 的构造函数中使用 Android 资源字符串

转载 作者:行者123 更新时间:2023-12-04 07:21:06 25 4
gpt4 key购买 nike

我的目标是为 Room @Entity 的构造函数添加一个默认值。默认值必须取决于用户的语言设置。 android框架建议的方式是使用资源字符串。

这是我的代码:

@Entity
data class ArmyEntity(
@PrimaryKey(autoGenerate = true)
val armyId: Long,
val userOwnerId: Long,
val name: String = R.string.untitled, // wrong type
val description: String = R.string.no_description_yet, // wrong type
val iconUri: String = "",
val lastEdit: Timestamp = Timestamp(System.currentTimeMillis())
)

我感兴趣的两行标有“错误类型”评论。调用 R.string.resource_string_name 返回资源 ID,而不是资源的内容(返回 Int,而不是 String)。

Android 文档建议这样获取字符串:

val string: String = getString(R.string.hello)

但问题是getString()函数是Context类的成员,可以在Activity中使用。但是带注释的房间实体不知道上下文。 ( Context page for reference )

我尝试将上下文作为构造函数参数传递,但不幸的是,数据类中的每个构造函数参数都必须是 valvar。据我所知,Room 会为类中的每个字段创建一个列。我应该怎么做才能提供依赖于语言的默认值?谢谢!

最佳答案

本地资源

在您的 Application 类中定义 context

class MyApplication : Application() {

companion object {
lateinit var context: Context
private set
}

override fun onCreate() {
super.onCreate()
context = this
}
}

然后在需要的地方使用MyApplication.context

import com.example.myapp.R
import com.example.myapp.MyApplication

@Entity
data class ArmyEntity(
@PrimaryKey(autoGenerate = true)
val armyId: Long,
val userOwnerId: Long,
val name: String = MyApplication.context.getString(R.string.untitled),
val description: String = MyApplication.context.getString(R.string.no_description_yet)
val iconUri: String = "",
val lastEdit: Timestamp = Timestamp(System.currentTimeMillis())
)

注意:Android Studio 会警告您内存泄漏。检查this question了解更多信息

对于系统资源

您可以导入 Resources使用 Resources.getSystem()R 类访问应用程序的资源。

import android.content.res.Resources
import com.example.yourapp.R

@Entity
data class ArmyEntity(
@PrimaryKey(autoGenerate = true)
val armyId: Long,
val userOwnerId: Long,
val name: String = Resources.getSystem().getString(R.string.untitled),
val description: String = Resources.getSystem().getString(R.string.no_description_yet)
val iconUri: String = "",
val lastEdit: Timestamp = Timestamp(System.currentTimeMillis())
)

关于android - 如何在 Kotlin Room Entity 的构造函数中使用 Android 资源字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68495022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com