简体   繁体   English

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

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

I have a kotlin module with code like this.我有一个 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
    
}

However I can't get string resource from this code,但是我无法从此代码中获取字符串资源,

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

string.xml:字符串.xml:

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

Please help so I can fetch string values into kotlin module from resources string.xml Thank you for the help.请帮助,以便我可以从资源 string.xml 将字符串值提取到 kotlin 模块中谢谢您的帮助。

You cannot use getString like that outside Activity or Application you have to use like below.您不能像下面那样在必须使用的 Activity 或 Application 之外使用getString

context.getString(R.string.textheader)

So you have to have the context to refer to String from string.xml else you won't be able to access it.因此,您必须具有从 string.xml 引用字符串的上下文,否则您将无法访问它。

use applications context:使用应用程序上下文:

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