2016-05-08 12 views
3

Ich habe einen Stringändern Farbe des Textview-Text in Android mit spannableString

1 Friend | O Reviews | 0 Coupons 

ich folgenden Code

SpannableString hashText = new SpannableString(TextUtils.concat(
       friendsText, 
       " | ", 
       reviewsText, 
       " | ", 
       couponsText 
     ).toString()); 

     Matcher matcher = Pattern.compile("\\s* | \\s*").matcher(hashText); 
     while (matcher.find()) 
     { 
      hashText.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), matcher.start(), matcher.end(), 0); 
     } 

     detailsText.setText(hashText); 

Ich möchte mich mit der Farbe ändern | zu blau von TextView ursprünglichen grauen Farbe. Der obige Code tut nichts. Was falsch mache ich darin.

Antwort

1

Versuchen Sie, wie dieses

String text = TextUtils.join(" | ", Arrays.asList(new String[]{"1 Friend", "1 Review", "1 Coupons"})); 

     Spannable spannable = new SpannableString(text); 

     int index = text.indexOf('|'); 
     while (index >= 0) { 
      spannable.setSpan(new ForegroundColorSpan(Color.BLUE), index, index + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
      index = text.indexOf('|', index + 1); 
     } 
     detailsText.setText(hashText); 

OutPut:

enter image description here

+0

"|" an mehreren Stellen platziert wird, funktioniert es für 1 | aber wo immer in der Zeichenfolge –

+0

@MuhammadUmar es funktioniert wo immer es gefunden '|'. Bitte lauf und sieh dir die Ausgabe an. Ich habe Screenshots für dasselbe hinzugefügt. –

1

die Sie interessieren,

Spannable spannable = new SpannableString(text); 

int index = text.indexOf(“|”); 

while (index >= 0) { 
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), index, index + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    index = text.indexOf(“|”, index + 1); 
} 
Verwandte Themen