0

I am developing a Calculator app and I want to display symbols like + - / * etc on a different color. Im using a TextView as my display.

I was able to do it when the buttons are being pressed with a code like this

coloredOperator = "<font color=#BED505>"+buttonPressed+"</font>";

textView.append(Html.fromHtml(coloredOperator));

However then I implemented a code on text change to order the operations when a new line is created on my textView, which looks something like this:

public void onTextChanged(CharSequence s, int start, int before, int count){
    String message = s.toString();

// I have a java class that takes cares of this             
    int lastPositionOfBreakCharacter = getLastIndexOfRegex(message, "\\-|\\+|\\/|\\*|\\^");


    int length = s.length();
    int breakPosition = length-lastPositionOfBreakCharacter;

    String text_view_text=t.getText().toString();
    StringBuffer sb=new StringBuffer(text_view_text);
    // So a new line is inserted before the last character +|-|* etc...
    sb.insert(breakPosition,"\n");
    textView.setText(sb);
}

The problem is that obviously this last functions strips my text view of all Spannables thus loosing style.

Is there any way to parse the text to find for the special characters, add the corresponding Spannables and then use .setText()?

Or do you have any other ideas on how to achieve what I'm after to?

Thanks!!!

Cruclax
  • 394
  • 3
  • 13
  • http://stackoverflow.com/questions/7364119/how-to-use-spannablestring-with-regex-in-android The Correct answer works for this question. – Cruclax Nov 21 '13 at 21:35

1 Answers1

1

How to use SpannableString with Regex in android?

The Correct answer works for this question.

////////////

 public class SpanTest extends Activity {

     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         String dispStr = "This has the string ABCDEF in it \nSo does this :ABCDEF - see!\nAnd again ABCD here";
         TextView tv = (TextView) findViewById(R.id.textView1);
        tv.setText(dispStr);
        changeTextinView(tv, "ABC", Color.RED);
    }

     private void changeTextinView(TextView tv, String target, int colour) {
         String vString = (String) tv.getText();
         int startSpan = 0, endSpan = 0;
         Spannable spanRange = new SpannableString(vString);

         while (true) {
             startSpan = vString.indexOf(target, endSpan);
             ForegroundColorSpan foreColour = new ForegroundColorSpan(colour);
             // Need a NEW span object every loop, else it just moves the span
             if (startSpan < 0)
                 break;
             endSpan = startSpan + target.length();
             spanRange.setSpan(foreColour, startSpan, endSpan,
                     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        tv.setText(spanRange);
    }
}
Community
  • 1
  • 1
Cruclax
  • 394
  • 3
  • 13