【问题标题】:How to get the Drawable name from imageview in android and get it's String name for comparing如何从android中的imageview获取Drawable名称并获取它的字符串名称以进行比较
【发布时间】:2015-04-07 09:33:33
【问题描述】:

我有两个可绘制的 applea 如何在我的代码中获取可绘制的名称并比较它们是否以相同的字母开头

社区编辑的问题

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

  1. 起初他想从 imageview id 中获取可绘制的 id。 (图像视图中显示的可绘制对象)

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

【问题讨论】:

  • 你试过String name = context.getResources().getResourceEntryName(imageResID); 吗?

标签: android android-layout android-imageview android-drawable


【解决方案1】:

更新答案

对于步骤 1

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

第二步

您应该通过

获取图像名称
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

}

【讨论】:

  • 我会随机获取图像视图中 26 的可绘制对象,因此我必须通过放置可绘制 id 来检查可绘制名称......对于 26,我可以通过任何方式获取可绘制名称imageview id 并获取哪个 drawable 连接到该 imageview
  • 让我们明确一点,你想先从 imageview id 中获取 drawable id,然后你想从获得的 drawable id 中获取 drawable 名称。我们清楚您的需求吗?
  • 我当前的答案应该为您的第二部分服务。
  • 但是如何通过imageview id获取drawable id??
  • 据我所知,没有 SDK 支持直接从 imageview 获取可绘制 id 的方法。您现在应该与回答者分享您的研究。
【解决方案2】:

你试过了吗?

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
}

【讨论】:

  • 是的,但是如何通过它的 imageview id 获取可绘制的 id ...因为我有 26 个可绘制的所以 ...静态地这样做会很长
【解决方案3】:

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

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

com.test.app:drawable/apple

当您想比较同一项目中的图像时,您可以轻松地将部分截断直到实际名称,因为它对于您的所有图像都是相同的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多