How to set background color of a View

2019-01-02 20:00发布

I'm trying to set the background color of a View (in this case a Button).

I use this code:

// set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();

It causes the Button to disappear from the screen. What am I doing wrong, and what is the correct way to change the background color on any View?

Thanks.

14条回答
ら面具成の殇う
2楼-- · 2019-01-02 20:03

and what is the correct way to change the background color on any View?

On any View? What you have is correct, though you should drop the invalidate() call.

However, some Views already have backgrounds. A Button, for example, already has a background: the face of the button itself. This background is a StateListDrawable, which you can find in android-2.1/data/res/drawable/btn_default.xml in your Android SDK installation. That, in turn, refers to a bunch of nine-patch bitmap images, available in multiple densities. You would need to clone and modify all of that to accomplish your green goals.

In short, you will be better served finding another UI pattern rather than attempting to change the background of a Button.

查看更多
人气声优
3楼-- · 2019-01-02 20:04
// set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();

The code does not set the button to green. Instead, it makes the button totally invisible.

Explanation: the hex value of the color is wrong. With an Alpha value of zero, the color will be invisible.

The correct hex value is 0xFF00FF00 for full opacity green. Any Alpha value between 00 and FF would cause transparency.

查看更多
孤独总比滥情好
4楼-- · 2019-01-02 20:05

When you call setBackgoundColor it overwrites/removes any existing background resource, including any borders, corners, padding, etc. What you want to do is change the color of the existing background resource...

View v;
v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);

Experiment with PorterDuff.Mode.* for different effects.

查看更多
怪性笑人.
5楼-- · 2019-01-02 20:09

try to add:

setBackgroundColor(Color.parseColor("#FF0000"));
查看更多
春风洒进眼中
6楼-- · 2019-01-02 20:10

This question talks about changing the background color of a view. In one of the answers, the person explains how to change the background color during runtime. Obviously you are going to look into how to modify other objects on the screen, but this should give you a good start by at least allowing you to modify the background color of the view on button click.

查看更多
余生无你
7楼-- · 2019-01-02 20:12

You can set the hex-color to any resource with:

View.setBackgroundColor(Color.parseColor("#e7eecc"));
查看更多
登录 后发表回答