Android - 如何解析Textview并在某些字符上添加Spannables?

时间:2013-11-19 23:43:26

标签: android textview spannable

我正在开发一个计算器应用程序,我希望在不同的颜色上显示+ - / *等符号。我使用TextView作为我的显示器。

当使用像这样的代码按下按钮时,我能够做到这一点

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

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

然而,我在文本更改上实现了一个代码,以便在我的textView上创建一个新行时对操作进行排序,如下所示:

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);
}

问题是,显然这最后一个功能剥离了我所有Spannables的文本视图,从而失去了风格。

有没有办法解析文本以找到特殊字符,添加相应的Spannables然后使用.setText()?

或者你对如何实现我的目标有任何其他想法吗?

感谢!!!

1 个答案:

答案 0 :(得分:1)

How to use SpannableString with Regex in android?

正确的答案适用于这个问题。

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

 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);
    }
}