getString Outside of a Context or Activity

后端 未结 12 2135
遥遥无期
遥遥无期 2020-11-28 01:12

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

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 01:33

    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);
    

提交回复
热议问题