Android View background changes unexpectedly

那年仲夏 提交于 2019-11-30 17:22:52

Without the code it's not easy... but I guess you are reusing the same ColorDrawable on multiple views and if you take a look at View.setBackgroundColor() source code :

public void setBackgroundColor(int color) {
    if (mBGDrawable instanceof ColorDrawable) {
        ((ColorDrawable) mBGDrawable).setColor(color);
    } else {
        setBackgroundDrawable(new ColorDrawable(color));
    }
}

You can see that it change the color of the ColorDrawable and don't create a new one each time. I'm pretty sure this is why you have this strange behavior.

EDIT

When you set the initial background color in xml with android:background you are doing this (according android doc):

Set the background to a given resource. The resource should refer to a Drawable object

According my understanding it will set the field View.mBGDrawable during the inflate. I suggest you to use View.setBackgoundDrawable(new ColorDrawable(the_color_int_code))) instead of setBackgroung(the_color_int_code). It should solve your issue.

Aalap

This usually happens if you have a view whose color is set in xml ex:

android:background="@color/cyan" 

Now this internally creates a new ColorDrawable - lets call it conceptual_drawable_cyan inside that view's class. Now when same view is assigned a different color programmatically using:

view.setBackgroundColor(newColor);

Internally this view instead of creating a different drawable it sets this newColor to drawable_cyan. Hence from this point onwards if you anywhere use

android:background="@color/cyan" 

the view would actually use conceptual_drawable_cyan with newColor.

Solution:

Instead of using setBackgroundColor to set color programmatically, use:

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        view.setBackground(new ColorDrawable(newColor));
    } else {
        view.setBackgroundDrawable(new ColorDrawable(newColor));
    }

Create the "colors.xml" file under the "values" folder. Example:

<?xml version="1.0" encoding="utf-8"?>
<resources><color name="pink">#f14fb7</color></resources>

Use view.setBackgroundResource(R.color.pink);

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