2014-08-30 87 views
0

我正在處理一個小型項目,但無法獲得預期的結果。我想要改變一個字符串的顏色奇怪的單詞和另一種顏色。誰能幫忙?我在這裏離開我目前的代碼:將顏色更改爲字符串中的奇數單詞

public void updateMessages() { 
     String groupMessage = "Admin says: Hi people\n Admin says: What's up?"; 

     TextView groupMessageBox = (TextView) this 
       .findViewById(R.id.groupMessageBox); 

     String[] str_array = groupMessage.split("\n|\\:"); 

     //Result str_array == Admin says, Admin says 

     for (int i = 0; i < str_array.length; i++) { 
//Get values of array   
String val1 = str_array[i]; 


//Only numbers pairs 
if (i % 2 == 0) { 
       //How to change the result to blue, for example? 
        Log.e("",val1); 
      }else{ 
        Log.e("",val1); 
       //How to change the result to red, for example? 
      } 
     } 
     groupMessageBox.setText(groupMessage); 
    } 

問候!

+1

看看[這裏](http://stackoverflow.com/questions/8405661/is-it-possible-to-change-the-text-color-in-a-string-to-multiple-colors-in -java) – 2014-08-30 15:22:33

+0

謝謝@SteveBenett,它的作品! ;-) – Adrian 2014-08-30 15:53:01

回答

0

如果你想的val1顏色變爲紅色,例如:

String coloredString = "<font color="#FF0000">" + val1 + "</font>"; 
str_array[i] = coloredString; 

然後外面的for循環,你可能想重新加入文字和重置的TextView:

String coloredMessage = // Join the strings together 
groupMessageBox.setText(Html.fromHtml(coloredMessage));