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:15

Several choices to do this...

Set background to green:

v.setBackgroundColor(0x00FF00);

Set background to green with Alpha:

v.setBackgroundColor(0xFF00FF00);

Set background to green with Color.GREEN constant:

v.setBackgroundColor(Color.GREEN);

Set background to green defining in Colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>     
    <color name="myGreen">#00FF00</color> 
    <color name="myGreenWithAlpha">#FF00FF00</color> 
</resources>

and using:

v.setBackgroundResource(R.color.myGreen);

and:

v.setBackgroundResource(R.color.myGreenWithAlpha);

or the longer winded:

v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreen));

and:

v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreenWithAlpha));
查看更多
萌妹纸的霸气范
3楼-- · 2019-01-02 20:17

For setting the first color to be seen on screen, you can also do it in the relevant layout.xml (better design) by adding this property to the relevant View:

android:background="#FF00FF00"
查看更多
只靠听说
4楼-- · 2019-01-02 20:19
mButton.setBackgroundColor(getResources().getColor(R.color.myColor));
查看更多
琉璃瓶的回忆
5楼-- · 2019-01-02 20:21

You can simple use :

view.setBackgroundColor(Color.parseColor("#FFFFFF"));
查看更多
冷夜・残月
6楼-- · 2019-01-02 20:21

You can simple use :

view.setBackgroundColor(Color.rgb(0, 198, 255));
查看更多
长期被迫恋爱
7楼-- · 2019-01-02 20:22

Stating with Android 6 use ContextCompact

        view.setBackgroundColor( ContextCompat.getColor(this, R.color.your_color));
查看更多
登录 后发表回答