setCompoundDrawables只在drawable设置为另一个imageview时工作?

时间:2017-06-02 09:08:53

标签: android

我正在改变drawable的颜色,然后将其设置为textview的左侧,但我观察的是一个奇怪的东西。 只有在我将drawable设置为其他图像视图并将其设置为textview之前,drawable left才有效。

  Drawable mDrawable = this.getResources().getDrawable(R.drawable.legendc);
                    mDrawable.setColorFilter(colorsActive[0], PorterDuff.Mode.SRC_IN);
                    mImageview.setImageDrawable(mDrawable);

                    mtextview.setCompoundDrawables(mDrawable, null, null, null);

如果我删除mImageview.setImageDrawable(mDrawable); 然后setCompoundDrawables不起作用,并且没有应用左侧drawable。 为什么会发生这种情况?

1 个答案:

答案 0 :(得分:3)

单独setCompoundDrawables()不起作用的原因可能与图像渲染和在Android中创建引用有关。每个Drawable变量中都有一个名为mCallback的参数。如果你想跳过设置ImageView它的值是null,否则它有一个WeakReference变量 - 这意味着app会说“看起来,引用绑定到内存中的某个地方,现在我可以使用它!“看起来setImageDrawable()方法会创建此绑定,而setCompoundDrawables()则不会。

我不是这个主题的专家,我发现的只是一种解决方法(也许你需要一个ImageLoader - 类似的对象来处理这个问题),但看起来像使用mtextview.setCompoundDrawablesWithIntrinsicBounds()效果很好。

//mImageview.setImageDrawable(mDrawable); You can delete this line

//Using this will not require to load your Drawable somewhere else
mtextview.setCompoundDrawablesWithIntrinsicBounds(mDrawable, null, null, null);
相关问题