有 Java 编程相关的问题?

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

java如何访问R.string。通过将字符串“xxx”作为参数传递给某个方法,从该方法获取xxx资源?

我的res/values/strings.xml中有许多字符串元素

因此,我需要一个方法getString(String abc),用于从strings.xml检索字符串:

public String getString(String abc){ // abc = address1

    String result;

    result = context.getResources().getString(R.strings.+abc);
}

如何基于参数中的字符串访问此方法中的字符串元素


共 (3) 个答案

  1. # 1 楼答案

     String abc="StringId";
     int resID = getResources().getIdentifier(abc, "string",  getPackageName()); 
    
  2. # 2 楼答案

    试试这个:

    Resources res = this.getResources(); 
     int resID = res.getIdentifier(imagename, "drawable", this.getPackageName());
    
  3. # 3 楼答案

    public String getString(String abc){ // Ex. abc = "address1"
    
       int resID = getResources().getIdentifier(abc, "string",  getPackageName()); 
    
       return context.getResources().getString(resID);
    }