Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android,从字符串中获取资源ID?_Java_Android_Resources_Android Resources - Fatal编程技术网

Java Android,从字符串中获取资源ID?

Java Android,从字符串中获取资源ID?,java,android,resources,android-resources,Java,Android,Resources,Android Resources,我需要将资源ID传递给我的一个类中的方法。它需要使用引用所指向的id和字符串。我应该如何最好地实现这一点 例如: R.drawable.icon 我需要得到这个的整数ID,但我还需要访问字符串“icon” 如果我只需要传递给这个方法的是“icon”字符串,那就更好了。您可以使用Resources.getIdentifier(),尽管在XML文件中使用字符串时需要使用字符串的格式,即包:drawable/icon@EboMike:我不知道Resources.getIdentifier()已存在

我需要将资源ID传递给我的一个类中的方法。它需要使用引用所指向的id和字符串。我应该如何最好地实现这一点

例如:

R.drawable.icon
我需要得到这个的整数ID,但我还需要访问字符串“icon”


如果我只需要传递给这个方法的是“icon”字符串,那就更好了。

您可以使用
Resources.getIdentifier()
,尽管在XML文件中使用字符串时需要使用字符串的格式,即
包:drawable/icon

@EboMike:我不知道
Resources.getIdentifier()
已存在

在我的项目中,我使用了以下代码:

public static int getResId(String resName, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(resName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

我刚刚发现一篇博文说,
Resources.getIdentifier()
比像我一样使用反射要慢

如果需要将字符串和int配对,那么映射如何

static Map<String, Integer> icons = new HashMap<String, Integer>();

static {
    icons.add("icon1", R.drawable.icon);
    icons.add("icon2", R.drawable.othericon);
    icons.add("someicon", R.drawable.whatever);
}
静态映射图标=新的HashMap();
静止的{
图标。添加(“icon1”,R.drawable.icon);
图标。添加(“icon2”,R.drawable.othericon);
添加(“someicon”,R.drawable.whatever);
}

如何从资源名称中获取应用程序资源id是一个非常常见且回答很好的问题

如何从资源名称中获取原生Android资源id,答案不太明确。 以下是我通过资源名称获取Android可绘制资源的解决方案:

public static Drawable getAndroidDrawable(String pDrawableName){
    int resourceId=Resources.getSystem().getIdentifier(pDrawableName, "drawable", "android");
    if(resourceId==0){
        return null;
    } else {
        return Resources.getSystem().getDrawable(resourceId);
    }
}
可以修改该方法以访问其他类型的资源。

这是基于@Macarse answer

使用此选项可以以更快速和代码友好的方式获取资源Id

public static int getId(String resourceName, Class<?> c) {
    try {
        Field idField = c.getDeclaredField(resourceName);
        return idField.getInt(idField);
    } catch (Exception e) {
        throw new RuntimeException("No resource ID found for: "
                + resourceName + " / " + c, e);
    }
}

我喜欢这样,这对我来说很有用:

    imageView.setImageResource(context.getResources().
         getIdentifier("drawable/apple", null, context.getPackageName()));

您可以使用此函数获取资源ID

public static int getResourceId(String pVariableName, String pResourcename, String pPackageName) 
{
    try {
        return getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}
因此,如果您想获得for可绘制的调用如下函数

getResourceId("myIcon", "drawable", getPackageName());
getResourceId("myAppName", "string", getPackageName());
对于字符串,你可以这样称呼它

getResourceId("myIcon", "drawable", getPackageName());
getResourceId("myAppName", "string", getPackageName());

既然您说您只想传递一个参数,而哪一个参数似乎无关紧要,那么您可以传入资源标识符,然后找到它的字符串名称,因此:

String name = getResources().getResourceEntryName(id);
这可能是获得这两个值的最有效方法。您不必费劲地从较长的字符串中查找“图标”部分

从字符串获取资源ID的简单方法。 此处resourceName是drawable文件夹中资源ImageView的名称,该文件夹也包含在XML文件中


在MonoDroid/Xamarin.Android中,您可以执行以下操作:

 var resourceId = Resources.GetIdentifier("icon", "drawable", PackageName);
但由于GetIdentifier在Android中不推荐使用,您可以这样使用反射:

 var resourceId = (int)typeof(Resource.Drawable).GetField("icon").GetValue(null);

我建议放置try/catch或验证您传递的字符串。

要从字符串资源名称获取可绘制id,我使用以下代码:

private int getResId(String resName) {
    int defId = -1;
    try {
        Field f = R.drawable.class.getDeclaredField(resName);
        Field def = R.drawable.class.getDeclaredField("transparent_flag");
        defId = def.getInt(null);
        return f.getInt(null);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        return defId;
    }
}

在res/layout/my_image_layout.xml中

<LinearLayout ...>
    <ImageView
        android:id="@+id/row_0_col_7"
      ...>
    </ImageView>
</LinearLayout>
科特林方法

inline fun <reified T: Class<*>> T.getId(resourceName: String): Int {
            return try {
                val idField = getDeclaredField (resourceName)
                idField.getInt(idField)
            } catch (e:Exception) {
                e.printStackTrace()
                -1
            }
        }
或:


@Macarse:目前,
getIdentifier()
必须进行两次反射查找。在上面的示例中,
getIdentifier()
将使用反射来获取
Drawable.class
,然后使用另一个反射查找来获取资源ID。这将解释速度差异。也就是说,两者都不是特别快,因此确实需要缓存(特别是在循环中使用时,或者在
列表视图中的行中使用时)。反射方法的一个大问题是,它对Android的内部结构做出了假设,这些假设在未来的版本中可能会发生变化。@commonware:没错。我正在检查android是如何实现的,它最终成为了一个本地调用。=>我将使用带有ID的整数数组。为ID使用字符串听起来不是正确的方法。为什么
上下文
参数?调用应该是getId(“icon”,R.drawable.class);非getResId(“图标”,上下文,可绘制的.class);是否可以以类似的方式获取保存到内部存储器的文件的ID?我有问题,因为我应该向我的图库提供ID数组而不是位置(以为它是适配器)。。thanks@Ewoks:它们在内部存储上没有ID。它们只是图像,如果您需要将它们加载到一组图像对象中并传递它们,您可能需要开始一个新问题。下面我的答案可能与此相反。传入资源id,然后使用
getResourceEntryName(id)
查找字符串名称。从较长的文本中找到“图标”不麻烦。谢谢,伙计,这真的很有帮助。。我找了很多,但都没找到。通过查看您的答案,我发现
getIdentifier
的第二个参数必须是
id
。安卓开发网站甚至没有提到这一点。你从哪里得到这些信息的?现在.getResources().getDrawable已被弃用
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.LOLLIPOP){return mContext.getDrawable(resourceId);}否则{return mContext.getResources().getDrawable(resourceId);}
让一个函数只调用另一个函数并“处理”可能的异常有什么意义?直接调用getResources().getIdentifier().Upvoted以澄清如何传入类型以获取不同种类或资源。android开发人员文档没有详细信息,先前答案中的“id”不适用于字符串。如果您只需为您的答案提供更多信息会更好。谢谢。一切正常。我使用了以下命令:
view.context.resources.getIdentifier(“drawable/item\u car\u$position”,null,context.packageName)
。效果非常好。最佳答案。
<LinearLayout ...>
    <ImageView
        android:id="@+id/row_0_col_7"
      ...>
    </ImageView>
</LinearLayout>
String row = "0";
String column= "7";
String tileID = "row_" + (row) + "_col_" + (column);
ImageView image = (ImageView) activity.findViewById(activity.getResources()
                .getIdentifier(tileID, "id", activity.getPackageName()));

/*Bottom code changes that ImageView to a different image. "blank" (R.mipmap.blank) is the name of an image I have in my drawable folder. */
image.setImageResource(R.mipmap.blank);  
inline fun <reified T: Class<*>> T.getId(resourceName: String): Int {
            return try {
                val idField = getDeclaredField (resourceName)
                idField.getInt(idField)
            } catch (e:Exception) {
                e.printStackTrace()
                -1
            }
        }
val resId = R.drawable::class.java.getId("icon")
val resId = R.id::class.java.getId("viewId")