Mingdi
Mingdi

Reputation: 185

How to set two views background color same/equal in code

I tried doing:

view1.background = view2.background

but it did not do anything. I then tried getting the background of view2 and did something like:

view1.setBackgroundColor(view2.getBackgroundColor)

However, there is no function to get background color of a view. How can I achieve this?

Upvotes: 3

Views: 172

Answers (3)

Lenoarod
Lenoarod

Reputation: 3610

Here are a method setBackgroundColor to set the view the background. we can also use the setBackground to set. we see they source code.

public void setBackgroundColor(@ColorInt int color) {
        if (mBackground instanceof ColorDrawable) {
            ((ColorDrawable) mBackground.mutate()).setColor(color);
            computeOpaqueFlags();
            mBackgroundResource = 0;
        } else {
            setBackground(new ColorDrawable(color));
        }
    }

public void setBackground(Drawable background) {
        //noinspection deprecation
        setBackgroundDrawable(background);
    }

the param for setBackgroundColor is an int color, but the API gives a method getBackground, it returns the drawable.

public Drawable getBackground() {
        return mBackground;
    }

so we can do as the following:

Drawable background = v1.getBackground();
v2.setBackground(background)

At the same, if we want to use the setBackgroundColor to do it, we have to get the int color. but that it requires the background is ColorDrawable

ColorDrawable background = (ColorDrawable)v1.getBackground();
int color = background.getColor();
v2.setBackgroundColor(color)

so I suggest you use the first way. that make the two view background same.

for the reason, why you can not directly assign the value. that because after the background set, the UI thread in android needs to reDraw, in that situation the config can take the effect. if you want to know more, you can see the setBackgroundDrawable method in view source code.

Upvotes: 1

Kanika
Kanika

Reputation: 61

        View view1 = findViewById(R.id.view1);
        View view2 = findViewById(R.id.view2);
        ColorDrawable viewColor = (ColorDrawable) view1.getBackground();
        int colorId = viewColor.getColor();

        view2.setBackgroundColor(colorId);

Upvotes: 0

user12340963
user12340963

Reputation:

You have to do more methods and get it as this

 j.background = buttonContinueFirst?.background?.current

Upvotes: 0

Related Questions