如何从 android 中的 imageview 中获取 Drawable 名称并获取它的字符串名称以进行比较

How to get the Drawable name from imageview in android and get it's String name for comparing

我有两个 drawable applea 如何在我的中获取 drawable 名称编码并比较它们以相同的字母开头

社区编辑的问题

提问者实际上是在求2个问题-

  1. 一开始他想从imageview id中得到drawable id。 (图像视图中显示的可绘制对象)

  2. 然后他想从步骤 1 中获得的 drawable id 中获取 drawable 名称。

更新答案

对于第 1 步

没有直接的方法。您需要通过 setTag() 在图像视图的 Tag 中保存 drawable id。然后你可以通过图像视图的 getTag() 检索。

第 2 步

您应该通过

获取图像名称
String imageName1 = context.getResources().getResourceEntryName(R.drawable.apple);
// now imageName1 should contain "apple".

String imageName2 = context.getResources().getResourceEntryName(R.drawable.a);
// now imageName2 should contain "a".

if(imageName1.toLowerCase().charAt(0) == imageName2.toLowerCase().charAt(0))

{

  // starting character 'a' is matching

}

你试过吗?

String name1 = getResources().getResourceEntryName(R.drawable.drawable_id_1);
String name2 = getResources().getResourceEntryName(R.drawable.drawable_id_2);

if (name1.startsWith("a") && name2.startsWith("a")) {
    // do something
}

通过getResources().getResourceName(R.drawable.XXXX)获取完整的资源名称。这将 return 给你一个形式为 package:type/entry 的字符串。

例如,我的项目在我的资源中有包 com.test.app 和一个名为 apple.png 的可绘制对象。调用我提到的方法结果将是:

com.test.app:drawable/apple

如果您想比较同一项目中的图像,您可以轻松截断实际名称部分,因为所有图像都相同。