Strings.xml is useful for managing constants, but make a note of how to call it in a class that does not inherit Activity or Fragment.
I created a context in a class that inherited the Application class, and created a function for getting constants so that the calling code could be cut as much as possible.
Model.java
public class Model extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = this;
}
/**
*Constant acquisition function
* strings.You can get the constants defined in xml from anywhere
* @param resId R.string.resId
* @return String constant
*/
public static String getConst(int resId) {
return context.getResources().getString(resId);
}
}
strings.xml
<string name="chat_list_delete_button_label">DELETE</string>
The caller can call with the following description
Model.getConst(R.string.chat_list_delete_button_label);
that's all.
I hope it will be helpful to anyone.
Recommended Posts