可绘制 == 可绘制?

drawable == drawable?(可绘制 == 可绘制?)

本文介绍了可绘制 == 可绘制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题...:

在我的活动中,我有一个 ImageView 和一个 Button.我希望 Button 仅在 ImageView 显示某个可绘制对象时执行操作.是的,这意味着 ImageView 在各种可绘制对象之间进行动画处理,这些可绘制对象不会中断我想做的事情.

In my activity I have an ImageView and a Button. I want the Button to perform an action ONLY when the ImageView displays a certain drawable. And yes, this means that the ImageView is animating between various drawables that is coded such that it does not interrupt with what I want done.

ImageView imgview = (ImageView)findViewById(R.id.imgviewsid);
Resources res = getResources();
Drawable acertaindrawable = res.getDrawable(R.drawable.thecertaindrawable);
Drawable variabledrawable = imgview.getDrawable();

    if (variabledrawable == acertaindrawable)
    {
            //does something
    }

没有用.我已将其缩小到if (variabledrawable == acertaindrawable)"这一行的错误.虽然 Eclipse 不会公然报告 Android 无法识别两个可绘制对象是否相同的错误,但我已经测试了代码的其他区域,并且似乎一切正常.

It didn't work. And I've narrowed it down to the fault of the line "if (variabledrawable == acertaindrawable)". While Eclipse does not blatantly report errors that Android cannot recognize if two drawables are the same, I've tested the other areas of the code and all seem to work fine.

推荐答案

正如 Itsik 所解释的,即使两个变量都包含对看起来"相同的对象的引用,它们也是 2 个不同的对象实例.

As explained by Itsik, even if both variables contain references to objects that 'look' the same, they are 2 different objects instances.

== 运算符比较引用.只有当两个变量都引用同一个对象实例时,它才返回 true,即.相同的内存空间.

The == operator compares references. It returns true only if both variables refer to the same object instance ie. the same memory space.

Drawable 和 BitmapDrawable 都没有实现特定的 .equals() 方法,该方法可以用于检查 2 个实例是否包含相同的数据,因此 Mathias Lin 提示尝试 .equals() 将不起作用.

Neither Drawable nor BitmapDrawable implement a specific .equals() method that could have been adapted to check that 2 instances contain the same data, so Mathias Lin hint to try .equals() will not work.

您可以按照Itsik 的建议而不用扩展Drawable 做的是使用View.setTag() 和View.getTag() 方法.这些方法允许将您选择的任何对象附加到视图并稍后检索它.通过在每次更改其内容时将一个简单的标识符(无论是技术整数标识符还是定义位图来源的 url)附加到您的 ImageView,您将能够轻松识别它.

What you could do, following Itsik's advice without having to extend Drawable, is use the View.setTag() and View.getTag() methods. These methods allow to attach any Object of your choice to a View and retrieve it later. By attaching a simple identifier (be it a technical integer identifier or a url defining the source of the bitmap) to your ImageView each time you change its content, you will be able to recognize it easily.

这篇关于可绘制 == 可绘制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:可绘制 == 可绘制?

基础教程推荐