Android编程实现TextView部分颜色变动的方法

时间:2022-12-04 15:42:40

本文实例讲述了Android编程实现TextView部分颜色变动的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class StringHandleExampleActivity extends Activity {
  /** Called when the activity is first created. */
  private TextView textView;
  private String tempStr = "abcd12我的中古zx9yu5!f3,,";
  private StringBuffer sb;
  private List<Integer> list;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    sb = new StringBuffer();
    list = new ArrayList<Integer>();
    textView = (TextView) findViewById(R.id.textView);
    for (int i = 0; i < tempStr.length(); i++) {
      if (matcherReg(String.valueOf(tempStr.charAt(i)))) {
        list.add(i);
      }
    }
    SpannableStringBuilder style=new SpannableStringBuilder(tempStr);  
    for (int i = 0; i < list.size(); i++) {
      System.out.println(list.get(i)+", ");
//      style.setSpan(new BackgroundColorSpan(Color.RED),list.get(i),list.get(i)+1,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);   //设置指定位置textview的背景颜色
      style.setSpan(new ForegroundColorSpan(Color.RED),list.get(i),list.get(i)+1,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);   //设置指定位置文字的颜色
    }
    textView.setText(style);
  }
  private boolean matcherReg(CharSequence c){
    String regEx="[^0-9]"
    Pattern p = Pattern.compile(regEx); 
    Matcher m = p.matcher(c.toString()); 
    if (m.matches()) {
      return false;
    }
    return true;
  }
}

希望本文所述对大家Android程序设计有所帮助。