【问题标题】:Comparing Drawables in Android not working properly比较 Android 中的 Drawable 无法正常工作
【发布时间】:2014-10-28 21:31:38
【问题描述】:

我为 ImageButton 编写 onClick 方法,我必须将按钮中的图像与资源文件夹中的另一个图像进行比较才能做一些事情。 这是我写的代码,我放了一些日志消息:

public void onClick(View v){
    Log.e(LOGTAG, "bolarojo: "+getResources().getDrawable(R.drawable.bolarojo).getConstantState().toString());
    Log.e(LOGTAG, "bolaclic: "+v.getBackground().getConstantState().toString());
    if(v.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.bolarojo).getConstantState())){
        Log.e(LOGTAG, "buh");

它显示: bolarojo: android.graphics.drawable.BitmapDrawable$BitmapState@4106ac08 bolaclic: android.graphics.drawable.StateListDrawable$StateListState@41070780 由于 v 持有 R.drawable.bolarojo 日志消息不应该相同吗?无论如何,我不明白为什么它不显示“buh”。

【问题讨论】:

    标签: android drawable imagebutton


    【解决方案1】:

    如果您查看正在处理的对象类型,您会发现其中一个对象具有BitmapState 类型的常量状态,而另一个具有StateListState。自然,比较两个不同类型的对象会导致它们不相等。即使那样,两个ConstantStates 也不能保证相等,即使它们来自同一个drawable。与其直接比较背景,不如从外部跟踪状态。这可能会更容易、更可靠。

    【讨论】:

    • 您能否再解释一下您所说的“从外部跟踪状态”是什么意思?现在我知道哪个是错误,但不知道如何解决。
    • 没有更多上下文我不能给你一个具体的例子,但基本上你只想维护另一个跟踪的变量,例如,如果你改变了背景,它就是这样。
    【解决方案2】:

    好吧,我终于解决了。我做了一个从 View 到 ImageButton 的演员表

    ImageButton bla=(ImageButton)v;
    

    然后我使用了 getDrawable() 方法,它工作正常:D

    bla.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.bolarojo).getConstantState());
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多