我正在尋找一種方法來查找TextView上的不同字符串,並將其替換爲樣式化的SpannableStrings。如何替換TexView的SpannableStrings上的多個字符串?
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);
}
}
這個偉大的工程,但我不知道如何去適應它使用與是否多串:
我How to use SpannableString with Regex in android?,不只是對於單個字符串中找到這段代碼。 我試着用SpannableStringBuilder.replace重新實現它,所以我可以多次運行該方法,同時保持以前的樣式但失敗。
任何想法?
謝謝!
非常好,很簡單。謝謝! – Cruclax