我发现R.string非常棒,可以将硬编码的字符串排除在代码之外,我希望在与应用程序中的模型一起工作的实用程序类中继续使用它来生成输出。例如,在本例中,我从活动外部的模型生成了一封电子邮件。

是否可以在上下文或活动之外使用getString ?我想我可以通过目前的活动,但似乎没有必要。如果我说错了,请指正!

编辑:我们可以在不使用上下文的情况下访问资源吗?


当前回答

是的,我们可以不使用“上下文”来访问资源

你可以使用:

Resources.getSystem().getString(android.R.string.somecommonstuff)

... 在应用程序的任何地方,甚至在静态常量声明中。 不幸的是,它只支持系统资源。

对于本地资源,请使用此解决方案。这不是小事,但很有效。

其他回答

如果你正在使用Hilt,你实际上可以注入上下文:

@Module
@InstallIn(SingletonComponent::class)
interface ResourceProvider {

    companion object {
    
    @Provides
    @Singleton
    @MyQualifier
    fun providesBaseUrl(@ApplicationContext context: Context): String = with(context) {
      getString(R.string.my_value)
    }
  }
}

您可以在Kotlin中通过创建一个扩展Application的类来实现这一点,然后使用它的上下文来调用代码中的任何地方的资源

你的App类看起来是这样的

 class App : Application() {
    override fun onCreate() {
        super.onCreate()
        context = this
    }

    companion object {
        var context: Context? = null
            private set
    }
}

在AndroidManifest.xml中声明你的Application类(非常重要)

<application
        android:allowBackup="true"
        android:name=".App" //<--Your declaration Here
        ...>
        <activity
            android:name=".SplashActivity"  android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity"/>
    </application>

要访问字符串文件,请使用以下代码

App.context?.resources?.getText(R.string.mystring)

从赫姆拉吉的回应来看,最好的方法是:

应用程序类

class App : Application() {

    companion object {
        lateinit var instance: Application
        lateinit var resourses: Resources
    }


    // MARK: - Lifecycle

    override fun onCreate() {
        super.onCreate()
        instance = this
        resourses = resources
    }

}

舱单上的声明

<application
        android:name=".App"
        ...>
</application>     

常量类

class Localizations {

    companion object {
        val info = App.resourses.getString(R.string.info)
    }

}

使用

textView.text = Localizations.info

我使用 getContext () .getApplicationContext () .getString (R.string.nameOfString); 这对我很管用。

不幸的是,你能访问任何字符串资源的唯一方法是一个上下文(即一个活动或服务)。在这种情况下,我通常做的是简单地要求调用者传递上下文。