android how to use string resource in a java class

后端 未结 4 1080
说谎
说谎 2020-12-29 20:04

In my java class I want to use a string resource from strings.xml.

for that I have to use like below,

getString(R.string.address)

i

4条回答
  •  梦毁少年i
    2020-12-29 20:28

    You can create a static Application Context in your custom Application class

    public class App extends Application{
    
        private static Context mContext;
    
        @Override
        public void onCreate() {
            super.onCreate();
            mContext = getApplicationContext();
        }
    
        public static Context getContext(){
            return mContext;
        }
    }
    

    Then you just need to call App.getContext().getResources() to get any resource values.

    Just remember that this Context is Application type, so there are things that this Context is not good to use. Read this for further info.

提交回复
热议问题