[Java] [Android 9.0 Pie] Example of how to call strings.xml other than Activity and Fragment

less than 1 minute read

at first

Strings.xml is convenient for managing constants, but make a note of how to call it in a class that does not inherit Activity or Fragment.

Implementation method

I generated a context in a class that inherits from the Application class, and created a function for obtaining constants so that the calling code could be trimmed even a little.

Model.java


public class Model extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    /**
     * Constant acquisition function
     * You can get constants defined in strings.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.