2013-02-15 73 views
0

我的意圖是帶兩個字符串。 1是消息的字符串,另一個是顏色的字符串。Android:如何使用字符串設置文本的顏色

下面的代碼顯示接收到2個字符串。 「消息」字符串顯示在正確工作的文本視圖中。不過,我需要字符串「messagecolor」來設置textview的顏色。

我有一個colors.xml文件,其中定義了藍色,綠色和紅色的顏色。

所以如果字符串「messagecolor」是藍色的文字將是藍色的。紅色和綠色也是一樣。如果字符串「messagecolor如果不是藍色,紅色或綠色,則文本將只顯示爲黑色。

如果有人可以幫我解決這個會很感激。

謝謝

// Get the message from the intent 
    Bundle bundle = getIntent().getExtras(); 
    String messagecolor = bundle.getString(MainActivity.EXTRA_MESSAGE_COLOR); 
    String message = bundle.getString(MainActivity.EXTRA_MESSAGE); 


    // Create the text view 
    TextView textView = new TextView(this); 
    textView.setTextColor(getResources().getColor(R.color.blue)); 
    textView.setTextSize(100); 
    textView.setText(message); 

回答

3

而不是試圖以匹配其顏色代表由串,你爲什麼不通過資源ID本身?

0

嘗試

if (message.equals("messageBlue")) { 
    textView.setTextColor(getResources().getColor(R.color.blue)); 
} else if (message.equals("messageGreen")) { 
    textView.setTextColor(getResources().getColor(R.color.green)); 
} else if (message.equals("messageRed")) { 
    textView.setTextColor(getResources().getColor(R.color.red)); 
} else //default 
    textView.setTextColor(getResources().getColor(R.color.black)); 
0
text.setText(Html.fromHtml("<font color='red'>R</font>"));