L. Fourde
L. Fourde

Reputation: 89

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?

Upvotes: 0

Views: 1540

Answers (2)

Abu Yousuf
Abu Yousuf

Reputation: 6107

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){

 }

Upvotes: 3

Palak Darji
Palak Darji

Reputation: 1114

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.

Upvotes: 1

Related Questions