【问题标题】:How to take R.string value instead of hardcoded value, if it's a class field?如果它是类字段,如何获取 R.string 值而不是硬编码值?
【发布时间】:2017-07-05 22:59:29
【问题描述】:

比如我想拿这个

public class SomeClass {
    public static final String GREET_STRING = "Hello!";
    //...

并将其更改为:

public class SomeClass {
    public static final String GREET_STRING = getString(R.string.greet_string);
    //...

这可以做到吗,还是我需要某种上下文实例化来获取字符串加载的资源?

【问题讨论】:

    标签: java android xml string resources


    【解决方案1】:

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

    【讨论】:

    • 所以我必须将上下文传递给类并以这种方式设置字符串?
    • 您可以将类字段设置为R.string.xxxxx,但您必须在上下文中这样做。您可以将上下文传递给类,但将字段设置在 Activity 中会更有意义
    • SomeClass sc = new SomeClass(); sc.field = getString(R.string.xxxxx);
    【解决方案2】:

    试试这个:

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

    资源/值/字符串:

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

    从 MainClass 调用 SomeClass

    public class MainClass extends SomeClass {
        private final static String TAG = MainClass.class.getName();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // call SomeClass from MainClass
            Log.i(TAG, SomeClass.GREET_STRING(this));
        }
    }
    

    【讨论】:

      【解决方案3】:

      有两种方法可以访问类中没有扩展Activity或Fragment的字符串。

      1. ContextActivity 传递给类构造函数

        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);
        }
        
      2. 第二种方法是如果您不想将上下文传递给类。您需要创建应用程序的实例和静态函数获取实例。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-10
        • 2011-10-09
        • 2019-12-29
        • 1970-01-01
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        • 2014-01-14
        相关资源
        最近更新 更多