简体   繁体   中英

Android: How to Convert String RGB Value to Color to use in View

I get the following string value from the db: "rgb(105, 105, 105)"

I tried Color.parseColor() but it wasn't right option.

I try to use it with view.setBackgroundColor()

Is there a way for this in Java/Android?

For "rgb(105, 105, 105)" this format you have to parse it manually. Try this code:

  try{

    String str = "rgb(105, 105, 105)";
    String splitStr = str.substring(str.indexOf('(') + 1, str.indexOf(')'));
    splitString = splitStr.split(",");

    int colorValues[] = new int[splitString.length];
    for (int i = 0; i < splitString.length; i++) {
        colorValues[i] = Integer.parseInt(splitString[i].trim());
    }

    int color = Color.rgb(colorValues[0], colorValues[1],colorValues[2]);
    view.setBackgroundColor(color); 

 }catch(Exception ex){

 }

Short and Simple:

view.setBackgroundColor(Color.rgb(105, 105, 105));

Edit: Mr Abu has given answer with parsing. Its complete answer, use it. I will discard my answer.

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