Java/Android String to Color conversion

15,654

Solution 1

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String, int)

For example:

titlebar.setBackgroundColor(Integer.parseInt("545455", 16)+0xFF000000);

Solution 2

What about titlebar.setBackgroundColor(Color.parseColor("#545455"));

Share:
15,654
Paul
Author by

Paul

Updated on July 21, 2022

Comments

  • Paul
    Paul almost 2 years

    I'm making an app and I'd like to be able to set various colors via user input(edittext) and hex values e.g. #eeeeee and so on. Problem is I cannot seem to figure out how to convert them.

    If I do something in code like this it works fine: titlebar.setBackgroundColor(0xFF545455);

    However if I retrieve a value via the edittext say "545455" I cannot get it work

              String tbColor = tb_color.getText().toString();             
              String value = "0xFF" + tbColor;  
              int setColor = Integer.valueOf(value);
              titlebar.setBackgroundColor(setColor);
    

    Anyone have any ideas on how to accomplish this?

  • Paul
    Paul over 13 years
    That produces a value of 5526613 and doesn't correctly set to the right color.
  • Luis Pena
    Luis Pena almost 10 years
    Worked perfectly! But please could you help me understand why adding: "+0xFF000000" made it work??
  • Allan Ramírez
    Allan Ramírez over 9 years
    Luis Alberto, because the 545455 replaces the 000000 after the 0xFF is just like: 850 + 100000 = 100850 (but in hexadecimal format) BTW 0xFF defines the alpha (transparency)