在 ImageView 中获取可绘制对象的 ID
我有一个 ImageView
并在它上面设置了一个 drawable.现在我需要动态获取 ImageView
的点击事件的 drawable 的 ID.我怎样才能得到它?
I have one ImageView
and set a drawable on it. Now I need to get the ID of the drawable on click event of ImageView
dynamically. How can I get it?
imgtopcolor = (ImageView) findViewById(R.id.topcolor);
imgtopcolor.setImageResource(R.drawable.dr); // How do I get this back?
现在在 imgtopcolor
的触摸事件上,我需要 drawable id,因为我每次都设置不同的 drawable 并且想将 drawable 与其他的进行比较
Now on touch event of imgtopcolor
i want to need drawable id because I am setting different drawable each time and want to compare the drawable with other
如果我理解正确的话,这就是你正在做的事情.
I think if I understand correctly this is what you are doing.
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
switch(getDrawableId(imageView)) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
break;
}
});
对吧?所以函数 getDrawableId()
不存在.您无法获得实例化可绘制对象的 id,因为该 id 只是对设备上有关如何构造可绘制对象的数据位置的引用.一旦构建了可绘制对象,它就无法取回用于创建它的 resourceId.但是你可以使用标签
Right? So that function getDrawableId()
doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
// See here
Integer integer = (Integer) imageView.getTag();
integer = integer == null ? 0 : integer;
switch(integer) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
imageView.setTag(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
imageView.setTag(R.drawable.foo);
break;
}
});