简体   繁体   中英

set background color: Android

How Do I set the background color of my android app. When I try:

LinearLayout li=(LinearLayout)findViewById(R.id.myLayout);
li.setBackgroundColor(Color.parseColor("#rrggbb"));

My app always crashes. Could someone help me out. Thanks

 Color.parseColor("#rrggbb") 

instead of #rrggbb you should be using hex values 0 to F for rr, gg and bb:

eg Color.parseColor("#000000") or Color.parseColor("#FFFFFF")

Source

From documentation:

public static int parseColor (String colorString):

Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'

So I believe that if you are using #rrggbb you are getting IllegalArgumentException in your logcat

Source

Alternative:

Color mColor = new Color();
mColor.red(redvalue);
mColor.green(greenvalue);
mColor.blue(bluevalue);
li.setBackgroundColor(mColor);

Source

This question is a old one but it can help for others too.

Try this :

    li.setBackgroundColor(getResources().getColor(R.color.blue));

    or

    li.setBackgroundColor(getResources().getColor(android.R.color.red));

    or

    li.setBackgroundColor(Color.rgb(226, 11, 11));


    or
    li.setBackgroundColor(Color.RED)

Try this:

li.setBackgroundColor(android.R.color.red); //or which ever color do you want

EDIT: Posting logcat file would also help.

By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:

android:background="#fff"
        int R = 111;    //My be assigned dynamic value
        int G = 111;    //My be assigned dynamic value
        int B = 111;    //My be assigned dynamic value
        
        getWindow().getDecorView().setBackgroundColor(Color.rgb(R, G, B));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM