Strange behavior of inflated buttons when changing one's color

淺唱寂寞╮ 提交于 2019-12-01 11:31:07

It seems that I've already solved my problem. That was a GradientDrawable.mutate() method which had to be called to prevent such behavior:

Button button = (Button) buttonView;
GradientDrawable gradientDrawable = (GradientDrawable) button.getBackground();
gradientDrawable.mutate(); // needed line
gradientDrawable.setColor(Color.RED);
gradientDrawable.invalidateSelf();

It guarantees that an initialized Drawable won't share its state with Drawables inflated from the same XML, as it was stated in a documentation:

Make this drawable mutable. This operation cannot be reversed. A mutable drawable is guaranteed to not share its state with any other drawable. This is especially useful when you need to modify properties of drawables loaded from resources. By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. Calling this method on a mutable Drawable will have no effect.

call invalidate on linear layout after adding the view,

linearLayout.addView(buttonLayout);
linearLayout.invalidate();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!