[英]get drawable from ImageView
我正在构建一个在主视图上有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)
?
将drawable的名称/ id存储在将其设置为ImageView的位置。 因此,您的类/活动中始终有一个包含当前图像标识符的成员变量。
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.因此,不要依赖这么多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.