2012-01-21 78 views
3

我有變量:如何將字符串轉換爲const類的int值?

String colorName = "BLUE"; 

我想設置這個顏色在android應用的塗料。它應該是這樣的:

paint.setColor ("Color." + colorName); 

但我收到錯誤警告,因爲setColor()函數的參數應該是int。 有什麼建議?謝謝。

回答

2

試試這個:

protected static final int colorName = Color.BLUE; 
paint.setColor(colorName); 

編輯:依我之見,你會得到你的顏色爲字符串。 所以你必須檢查它是什麼顏色,然後設置你的'colorName'變量。 事情是這樣的:

if(yourcolorstring.equals("Blue")){ 
    colorName = Color.BLUE; 
}else if(yourcolorstring.equals("Black")){ 
    colorName = Color.BLACK; 
}else{ 
    colorName = Color.WHITE; 
} 
+1

嗨Prexx,當我回答Oskar Kjellin時,我不知道const值。我可以從其他活動而不是「藍色」作爲字符串「Color.BLUE」接收,但我可以用它做什麼? –

+0

檢查我編輯的帖子。這是你的答案嗎? – Prexx

+0

太棒了!謝謝! –

2

你需要做的:

paint.setColor(Color.BLUE); 
+0

嗨Oskar Kjellin,這是我想要的。但我不知道顏色值,我把它當作String變量。我用其他活動的extras.getString()函數接收它。 –

+0

@tatiana_c這是不可能的。您可能必須使用反射或開關 –

+0

Oskar Kjellin,我認爲我同意你的觀點。我會嘗試Prexx的解決方案。謝謝。 –

1

至少在標準Java可以使用:

import javax.swing.text.html.CSS; 

String colorName = "fuchsia"; // "maroon", "rgb(1,20,30)", "#ff00aa" 
Color color = CSS.stringToColor(colorName); 

這是因爲HTML的支持;你也可以寫一個JLabel與Oracle的

"<html><span style='color:blue'>hello</span>" 

JDK 7 要顯示什麼文本常數是可行的,什麼格式:

/** 
    * Convert a "#FFFFFF" hex string to a Color. 
    * If the color specification is bad, an attempt 
    * will be made to fix it up. 
    */ 
static final Color hexToColor(String value) { 
    String digits; 
    int n = value.length(); 
    if (value.startsWith("#")) { 
     digits = value.substring(1, Math.min(value.length(), 7)); 
    } else { 
     digits = value; 
    } 
    String hstr = "0x" + digits; 
    Color c; 
    try { 
     c = Color.decode(hstr); 
    } catch (NumberFormatException nfe) { 
     c = null; 
    } 
    return c; 
} 

/** 
* Convert a color string such as "RED" or "#NNNNNN" or "rgb(r, g, b)" 
* to a Color. 
*/ 
static Color stringToColor(String str) { 
    Color color; 

    if (str == null) { 
     return null; 
    } 
    if (str.length() == 0) 
    color = Color.black; 
    else if (str.startsWith("rgb(")) { 
     color = parseRGB(str); 
    } 
    else if (str.charAt(0) == '#') 
    color = hexToColor(str); 
    else if (str.equalsIgnoreCase("Black")) 
    color = hexToColor("#000000"); 
    else if(str.equalsIgnoreCase("Silver")) 
    color = hexToColor("#C0C0C0"); 
    else if(str.equalsIgnoreCase("Gray")) 
    color = hexToColor("#808080"); 
    else if(str.equalsIgnoreCase("White")) 
    color = hexToColor("#FFFFFF"); 
    else if(str.equalsIgnoreCase("Maroon")) 
    color = hexToColor("#800000"); 
    else if(str.equalsIgnoreCase("Red")) 
    color = hexToColor("#FF0000"); 
    else if(str.equalsIgnoreCase("Purple")) 
    color = hexToColor("#800080"); 
    else if(str.equalsIgnoreCase("Fuchsia")) 
    color = hexToColor("#FF00FF"); 
    else if(str.equalsIgnoreCase("Green")) 
    color = hexToColor("#008000"); 
    else if(str.equalsIgnoreCase("Lime")) 
    color = hexToColor("#00FF00"); 
    else if(str.equalsIgnoreCase("Olive")) 
    color = hexToColor("#808000"); 
    else if(str.equalsIgnoreCase("Yellow")) 
    color = hexToColor("#FFFF00"); 
    else if(str.equalsIgnoreCase("Navy")) 
    color = hexToColor("#000080"); 
    else if(str.equalsIgnoreCase("Blue")) 
    color = hexToColor("#0000FF"); 
    else if(str.equalsIgnoreCase("Teal")) 
    color = hexToColor("#008080"); 
    else if(str.equalsIgnoreCase("Aqua")) 
    color = hexToColor("#00FFFF"); 
    else if(str.equalsIgnoreCase("Orange")) 
    color = hexToColor("#FF8000"); 
    else 
     color = hexToColor(str); // sometimes get specified without leading # 
    return color; 
} 

/** 
* Parses a String in the format <code>rgb(r, g, b)</code> where 
* each of the Color components is either an integer, or a floating number 
* with a % after indicating a percentage value of 255. Values are 
* constrained to fit with 0-255. The resulting Color is returned. 
*/ 
private static Color parseRGB(String string) { 
    // Find the next numeric char 
    int[] index = new int[1]; 

    index[0] = 4; 
    int red = getColorComponent(string, index); 
    int green = getColorComponent(string, index); 
    int blue = getColorComponent(string, index); 

    return new Color(red, green, blue); 
} 

/** 
* Returns the next integer value from <code>string</code> starting 
* at <code>index[0]</code>. The value can either can an integer, or 
* a percentage (floating number ending with %), in which case it is 
* multiplied by 255. 
*/ 
private static int getColorComponent(String string, int[] index) { 
    int length = string.length(); 
    char aChar; 

    // Skip non-decimal chars 
    while(index[0] < length && (aChar = string.charAt(index[0])) != '-' && 
      !Character.isDigit(aChar) && aChar != '.') { 
     index[0]++; 
    } 

    int start = index[0]; 

    if (start < length && string.charAt(index[0]) == '-') { 
     index[0]++; 
    } 
    while(index[0] < length && 
        Character.isDigit(string.charAt(index[0]))) { 
     index[0]++; 
    } 
    if (index[0] < length && string.charAt(index[0]) == '.') { 
     // Decimal value 
     index[0]++; 
     while(index[0] < length && 
       Character.isDigit(string.charAt(index[0]))) { 
      index[0]++; 
     } 
    } 
    if (start != index[0]) { 
     try { 
      float value = Float.parseFloat(string.substring 
              (start, index[0])); 

      if (index[0] < length && string.charAt(index[0]) == '%') { 
       index[0]++; 
       value = value * 255f/100f; 
      } 
      return Math.min(255, Math.max(0, (int)value)); 
     } catch (NumberFormatException nfe) { 
      // Treat as 0 
     } 
    } 
    return 0; 
} 
+0

嗨Joop Eggen,它看起來像有趣的東西,謝謝。我現在試過,但我收到錯誤消息「導入javax.swing無法解析」。我使用SDK 6.可能是因爲我編寫了一個android應用程序。 –

+0

對不起,我還沒有做過Android應用程序。我會通過CSS的有關代碼。 –

+0

顏色。parseColor是更好的答案。 –

2

如果你有顏色的長長的名單,你不想寫的if ... else if語句長序列,你也可以使用這個Map。鍵將是帶有顏色名稱的字符串,值爲您想要查找的恆定值。例如:

Map<String, Color> colors = new HashMap<String, Color>(); 
colors.put("BLUE", Color.BLUE); 
colors.put("RED", Color.RED); 
colors.put("GREEN", Color.GREEN); 

// To find the Color constant, look it up in the map: 
String text = "BLUE"; 
Color c = colors.get(text); 
if (c != null) { 
    paint.setColor(c); 
} else { 
    System.out.println("Unknown color: " + text); 
} 
+0

嗨,Jesper,謝謝你的回答。我沒有想到在這個方向上,我已經收到了parseColor()的確切答案,但是在我擁有的其他代碼區域中使用它是一個有趣的想法。 –