I\'ve found the R.string
pretty awesome for keeping hardcoded strings out of my code, and I\'d like to keep using it in a utility class that works with models i
In MyApplication
, which extends Application
:
public static Resources resources;
In MyApplication
's onCreate
:
resources = getResources();
Now you can use this field from anywhere in your application.
It's better to use something like this without context and activity:
Resources.getSystem().getString(R.string.my_text)
BTW, one of the reason of symbol not found error may be that your IDE imported android.R; class instead of yours one. Just change import android.R; to import your.namespace.R;
So 2 basic things to get string visible in the different class:
//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);
}
If you have a class that you use in an activity and you want to have access the ressource in that class, I recommend you to define a context as a private variable in class and initial it in constructor:
public class MyClass (){
private Context context;
public MyClass(Context context){
this.context=context;
}
public testResource(){
String s=context.getString(R.string.testString).toString();
}
}
Making an instant of class in your activity:
MyClass m=new MyClass(this);
Unfortunately, the only way you can access any of the string resources is with a Context
(i.e. an Activity
or Service
). What I've usually done in this case, is to simply require the caller to pass in the context.
Somehow didn't like the hacky solutions of storing static values so came up with a bit longer but a clean version which can be tested as well.
Found 2 possible ways to do it-
e.g.
data class MyModel(val resources: Resources) {
fun getNameString(): String {
resources.getString(R.string.someString)
}
}
Before you read: This version uses Data binding
XML-
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="someStringFetchedFromRes"
type="String" />
</data>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{someStringFetchedFromRes}" />
</layout>
Activity/Fragment-
val binding = NameOfYourBinding.inflate(inflater)
binding.someStringFetchedFromRes = resources.getString(R.string.someStringFetchedFromRes)
Sometimes, you need to change the text based on a field in a model. So you would data-bind that model as well and since your activity/fragment knows about the model, you can very well fetch the value and then data-bind the string based on that.