1. 程式人生 > >擷取字串,改變第N個字元的顏色;自定義方法,oncreat中呼叫

擷取字串,改變第N個字元的顏色;自定義方法,oncreat中呼叫

用到過很多次,每次在用的時候,思路就會斷線,以此特意寫出來,幫助自己記憶;

修改TextView 中部分文字的顏色

  1. textView = (TextView) findViewById(R.id.textview);  
  2. SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());  
  3. //ForegroundColorSpan 為文字前景色,BackgroundColorSpan為文字背景色
  4. ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);  
  5. ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE);  
  6. ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE);  
  7. ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN);  
  8. ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.YELLOW);  
  9. builder.setSpan(redSpan, 0
    1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  10. builder.setSpan(whiteSpan, 12, Spannable.SPAN_INCLUSIVE_INCLUSIVE);  
  11. builder.setSpan(blueSpan, 23, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  12. builder.setSpan(greenSpan, 34, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  13. builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
     
  14. textView.setText(builder);

  15.  

二、外部方法呼叫

private TextView tv_samplenumber_lan;

tv_samplenumber_lan=(TextView) findViewById(R.id.tv_samplenumber_lan);
tv_samplenumber_lan=dofor(tv_samplenumber_lan);
public static TextView dofor(TextView str){
    SpannableStringBuilder builder = new SpannableStringBuilder(str.getText().toString());
  //ForegroundColorSpan 為文字前景色,BackgroundColorSpan為文字背景色
ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
    if (str.getText().toString().substring(4,5).equals("*")){
    builder.setSpan(redSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }else if (str.getText().toString().substring(7,8).equals("*")){
     builder.setSpan(redSpan, 7,8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    str.setText(builder);
    return str;
}


特意附上大神給講解的例項程式碼