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

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

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


当前回答

BTW,符号未发现错误的原因之一可能是您的IDE导入了android.R;而不是你的班级。只需更改import android.R;导入你的。namespace. r;

要让字符串在不同的类中可见,有两个基本步骤:

//make sure you are importing the right R class
import your.namespace.R;

//don't forget about the context
public void some_method(Context context) {
   context.getString(R.string.YOUR_STRING);
}

其他回答

以下是基于Khemraj Sharma的回答,这是Kotlin版本,有一个额外的扩展作为奖励:

class App: Application() {

    override fun onCreate() {
        super.onCreate()
        mInstance = this
        res = resources
    }
    companion object{

        private var mInstance: App? = null
        private var res: Resources? = null

        fun getInstance(): App? {
            return mInstance
        }

        fun getRes(): Resources? {
            return res
        }
    }
}

然后我们可以创建一个扩展:

fun Int.resourceToString(): String {
    return App.getRes()?.getString(this) ?: "Not Found"
}

并直接在任何资源id上使用扩展:

var asString = R.string.my_string.resourceToString()

在MyApplication中,扩展Application:

public static Resources resources;

在MyApplication的onCreate中:

resources = getResources();

现在您可以在应用程序中的任何地方使用该字段。

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

如果你正在使用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)
    }
  }
}

# #独特的方法

# # App.getRes () .getString (R.string.some_id)

这将在应用程序的任何地方工作(Util类,对话框,片段或 应用程序中的任何类)

(1)创建或编辑(如果已经存在)你的应用程序类。

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getRes() {
        return res;
    }

}

(2)在manifest.xml <application标签中添加name字段。

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

现在可以开始了。在应用程序的任何地方使用app. getres (). getstring (r.r string.some_id)。