Android programming method for TextView part color change

  • 2020-11-20 06:14:29
  • OfStack

This article illustrates the Android programming method to realize the color change of TextView. To share for your reference, the details are as follows:


public class StringHandleExampleActivity extends Activity {
  /** Called when the activity is first created. */
  private TextView textView;
  private String tempStr = "abcd12 My middle 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);   // Set the specified location textview Background color  
      style.setSpan(new ForegroundColorSpan(Color.RED),list.get(i),list.get(i)+1,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);   // Sets the color of the text for the specified location  
    }
    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;
  }
}

I hope this article has been helpful in Android programming.


Related articles: