Strange behavior of inflated buttons when changing one's color

后端 未结 2 919
孤城傲影
孤城傲影 2021-01-15 12:18

I am trying to implement a dynamic button inflation for my Android application, based on an input specified by the user in real time. When clicked, button changes its color

相关标签:
2条回答
  • 2021-01-15 13:04

    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.

    0 讨论(0)
  • 2021-01-15 13:09

    call invalidate on linear layout after adding the view,

    linearLayout.addView(buttonLayout);
    linearLayout.invalidate();
    
    0 讨论(0)
提交回复
热议问题