【发布时间】:2019-01-21 10:47:03
【问题描述】:
我是 Android 和 Kotlin 的新手。我正在尝试创建一个ResourcesHelper class,以便从我的应用程序中的任何其他自定义类轻松访问我的自定义颜色和字体。但是在这个助手中,我没有任何上下文。我已经阅读了获取扩展 Application 类的上下文的方法,但是编译器说我无法在 ResourcesHelper 伴随对象中访问此上下文,因为它会造成内存泄漏。我最后也得到了可选的链接。
这是我希望能够使用它的方式:
class ResourcesHelper {
companion object {
val lightBlue = resources.getColor(R.color.lightBlue)
val customBlue = resources.getColor(R.color.customBlue)
// [...]
val fontAwesome = resources.getFont(R.font.fontawesome)
val lemonMilk = resources.getFont(R.font.lemonmilk)
}
}
enum class ButtonStyle {
MENU,
// [...]
VICTORY
}
class CustomButton(c: Context, attrs: AttributeSet) : Button(c, attrs) {
var isButtonActivated = false
fun setStyle(style: ButtonStyle) {
setBackgroundColor(ResourcesHelper.transparent)
when(style) {
ButtonStyle.MENU -> {
setText(R.string.menu_button)
typeface = ResourcesHelper.lemonMilk
setBackgroundColor(ResourcesHelper.customRed)
setTextColor(ResourcesHelper.white)
}
// [...]
ButtonStyle.VICTORY -> {
setText(R.string.victory_button)
typeface = ResourcesHelper.lemonMilk
setBackgroundColor(ResourcesHelper.customRed)
setTextColor(ResourcesHelper.white)
}
}
}
}
我也阅读了这篇文章 Android access to resources outside of activity,但它是用 Java 编写的,我不知道如何在 Kotlin 中进行操作。
我完全不知道该怎么做以及如何做到这一点......或者是否有更好的方法来实现从任何地方获取资源。
感谢您的帮助
【问题讨论】:
-
编译器说我无法在 ResourcesHelper 伴随对象中访问此上下文,因为它会造成内存泄漏 - 我认为这是一个警告,而不是错误。你也可以忽略它。应用上下文不能泄露
-
谢谢!所以我得到一个可选的上下文。
val myCustomColor = context!!.getColor(R.color.lightBlue)安全吗?我的 applicationContext 可以为空吗? -
我不明白你的意思。您使用应用程序类检索的上下文不可为空
-
我尝试复制类似stackoverflow.com/questions/9445661/… 的内容,Android Studio 将其转换为 Kotlin 并使上下文可为空。但是我可以直接在我的 ResourcesHelper 中直接执行
val context = Application().applicationContext,这样我就有了一个不可为空的上下文。 -
虽然如果我喜欢这样做,它会使应用程序崩溃并显示
Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109) at com...Common.ResourcesHelper.<clinit>(ResourcesHelper.kt:10)