在 ImageView 中获取可绘制对象的 ID [英] Get the ID of a drawable in ImageView

查看:38
本文介绍了在 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;
        }
    });

这篇关于在 ImageView 中获取可绘制对象的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆