有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java前缀字符串资源标识符,用于在运行时选择备用版本

通常,我使用以下方法从资源XML中获取字符串值:

String mystring = getResources().getString(R.string.mystring);

现在,我想根据一些运行时条件选择字符串的替代版本

String selectivestring;
if (someBooleanCondition)
  selectivestring= getResources().getString(R.string.mystring);
else 
  selectivestring= getResources().getString(R.string.theirstring);

到目前为止还不错,但由于我有很多这样的“可选字符串对”,我想有条不紊地为一种类型(比如说“my_u”)和另一种类型(比如“alt_u”)加上前缀:

String selectivestring1;
if (someBooleanCondition)
  selectivestring1= getResources().getString(R.string.my_string1);
else 
  selectivestring1= getResources().getString(R.string.alt_string1);
.
.
.
String selectivestring2;
if (someBooleanCondition)
  selectivestring2= getResources().getString(R.string.my_string2);
else 
  selectivestring2= getResources().getString(R.string.alt_string2);

(以上代码仅用于说明。我最终想做的是将其参数化,以便将其放入循环、数组或自己的访问器中)

如果Java中有一个预处理器,我就可以使用字符串连接来选择“my_uu”和“alt_u”前缀。但是,既然我知道没有,有没有一种方法、解决方法或建议可以在运行时修改字符串资源标识符,如上所述

注意:每个字符串的替代版本是not在不同的语言/区域设置中。我基本上是想把字符串的原始版本和备用版本放在一起,彼此相邻,放在同一个资源文件中,这样我就可以轻松地比较这两个版本


共 (1) 个答案

  1. # 1 楼答案

    首先,您的代码可以更好一些,如下所示:

    int resource = 
       someBooleanCondition ? 
           R.string.my_string2 : R.string.alt_string2;
    String selectivestring2 = getResources().getString(resource);
    

    正如你所描述的,这可以通过反射来实现,下面是一个非常简单的例子:

    package br;
    import java.lang.reflect.Field;
    
    final class R {
        public static final class string {
            public static final int alt_string1=0x7f060601;
            public static final int alt_string2=0x7f060101;
        }
    }
    public class StaticReflection {
    
        public static boolean globalVariable = false;
    
        //this would be android method getString
        public static String fakeGetString(int id){
            switch (id){
            case R.string.alt_string1: return "it";
            case R.string.alt_string2: return "works";
            default:
                return "O NOES";
            }
        }
    
        //static method
        public static String getResource(String resId) throws Exception {
            if (globalVariable){
                resId += "string1";
            } else {
                resId += "string2";
            }
            Field f = R.string.class.getDeclaredField(resId);
            Integer id = (Integer) f.get(null);
            return fakeGetString(id);
        }
    
        public static void main(String[] args) throws Exception {
            globalVariable=true;
            System.out.println(getResource("alt_"));
            globalVariable=false;
            System.out.println(getResource("alt_"));
        }
    }