【问题标题】:get drawable from ImageView从 ImageView 获取可绘制
【发布时间】:2012-05-24 10:13:01
【问题描述】:

我目前正在构建一个在主视图上有 6 张图像的应用,它会从我的 drawable 文件夹中生成随机图像(洗牌)

初始化套牌:

public static void initDecks() {
    int m = 0;
    for (int i = 0; i < suites.length; i += 1) {
        for (int j = 0; j < regularCards.length; j += 1) {
            regularDeck[m++] = "drawablw/" + suites[i] + regularCards[j]
                    + ".jpg";
        }
    }
    m = 0;
    for (int i = 0; i < suites.length; i += 1) {
        for (int j = 0; j < trickCards.length; j += 1) {
            trickDeck[m++] = "drawable/" + suites[i] + trickCards[j]
                    + ".jpg";
        }
    }

    Collections.shuffle(Arrays.asList(regularDeck));
    Collections.shuffle(Arrays.asList(trickDeck));
}

洗牌:

public static String[] getCards(int size) {
    String[] result = new String[size];
    for (int i = 0; i < size - 2; i += 1) {
        result[i] = regularDeck[i];
    }
    result[size - 1] = trickDeck[0];
    Collections.shuffle(Arrays.asList(result));
    return result;
}

在我的主要活动中,我将卡片分配给视图,当用户点击它们时,我想知道这张图片是特技卡片还是普通卡片。

有没有办法查出被点击的卡片是否是花样?类似if(image.getImageDrawable().equals(R.drawable.trick.jpg)?

【问题讨论】:

标签: android drawable android-imageview


【解决方案1】:

将可绘制对象的名称/ID 存储在您将其设置为 ImageView 的位置。因此,您的类/活动中始终有一个成员变量来保存当前图像标识符。

【讨论】:

    【解决方案2】:

    请查看此链接

    Get the ID of a drawable in ImageView

    基本上,当您在 ImageView 中设置图像并从您需要的位置获取时,您可以在 ImageView 标记中设置 id....

    【讨论】:

      【解决方案3】:
      public static Integer getDrawableId(ImageView obj)
          throws SecurityException, NoSuchFieldException,
          IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
              Field f = ImageView.class.getDeclaredField("mResource");
              f.setAccessible(true);
              Object out = f.get(obj);
              return (Integer)out;
      }
      

      我发现Drawable资源id存储在ImageView对象的mResource字段中。

      请注意,ImageView 中的 Drawable 可能并不总是来自资源 ID。它可能来自Drawable 对象或图像 Uri。在这些情况下,mResource 将重置为 0。因此,不要过分依赖。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多