繁体   English   中英

在 android 工作室中使用 kotlin 从字符串中获取文本

[英]Get text from string with kotlin in android studio

我有一个 kotlin 模块,代码如下。

class AppOpenManager(private val appLanding: AppLanding) : 
    Application.ActivityLifecycleCallbacks, LifecycleObserver{

    //.........OTHER CODE

    companion object {
        private const val TEXT_HEADER = getString(R.string.textheader)
    }

    //.........OTHER CODE
    
}

但是我无法从此代码中获取字符串资源,

private const val TEXT_HEADER = getString(R.string.textheader)

字符串.xml:

<resources>
    <string name="textheader">Lorem Ipsum</string>
</resources>

请帮助,以便我可以从资源 string.xml 将字符串值提取到 kotlin 模块中谢谢您的帮助。

您不能像下面那样在必须使用的 Activity 或 Application 之外使用getString

context.getString(R.string.textheader)

因此,您必须具有从 string.xml 引用字符串的上下文,否则您将无法访问它。

使用应用程序上下文:

private const val TEXT_HEADER = 
getApplicationContext().getResources().getString(R.string.textheader);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM