Java 如果R.string值为';那是一个班级?

Java 如果R.string值为';那是一个班级?,java,android,xml,string,resources,Java,Android,Xml,String,Resources,比如我想拿这个 public class SomeClass { public static final String GREET_STRING = "Hello!"; //... 并将其更改为: public class SomeClass { public static final String GREET_STRING = getString(R.string.greet_string); //... 这是可以做到的,还是我需要某种上下文实例化来获取字符

比如我想拿这个

public class SomeClass {
    public static final String GREET_STRING = "Hello!";
    //...
并将其更改为:

public class SomeClass {
    public static final String GREET_STRING = getString(R.string.greet_string);
    //...
这是可以做到的,还是我需要某种上下文实例化来获取字符串加载的资源?

要使用
getString()
您需要一个上下文。资源字符串不能是
static final
,因为字符串资源可能随着您更改区域设置而更改(如果您有多个字符串文件,例如
strings.xml(us)
strings.xml(uk)

请尝试以下操作:

public abstract class SomeClass extends AppCompatActivity {

    public static String GREET_STRING(Context context) {
        if (context == null) {
            return null;
        }
        return context.getResources().getString(R.string.greet_string);
    }
}
Res/值/字符串:

<resources>
    <string name="greet_string">Hello!</string>
</resources>

有两种方法可以访问不扩展活动或片段的类中的字符串

  • 上下文
    活动
    传递给类构造函数

    public class SomeClass {
        private Context context;
        public SomeClass(Context context) {
            this.context = context;
        }
        public static final String GREET_STRING = context.getString(R.string.greet_string);
    }
    
  • 第二种方法是,如果不想将上下文传递给类。您需要创建应用程序实例和静态函数get instance

    public class App extends Application {
            private static App instance = null;
            @Override
            public void onCreate() {
                super.onCreate();
                instance = this;
            }
            public static App getInstance() {
                // Return the instance
                return instance;
            }
    }       
    
    public class SomeClass {
            public static final String GREET_STRING = App.getInstance().getString(R.string.greet_string);
        }
    

  • 因此,我必须将上下文传递给类并以这种方式设置字符串?您可以将类字段设置为
    R.string.xxxxx
    ,但必须使用上下文。您可以将上下文传递给类,但在
    活动中设置字段更为合理;sc.field=getString(R.string.xxxxx)
    
    public class App extends Application {
            private static App instance = null;
            @Override
            public void onCreate() {
                super.onCreate();
                instance = this;
            }
            public static App getInstance() {
                // Return the instance
                return instance;
            }
    }       
    
    public class SomeClass {
            public static final String GREET_STRING = App.getInstance().getString(R.string.greet_string);
        }