我正在尝试用跨度替换Editable
返回的一部分。getText()
我已经尝试过getText().replace()
,但这仅适用于CharSequences
.
我尝试这样做的原因是我可以一个EditText
接一个地突出显示一个部分(经过一小段延迟),而不是遍历并突出显示整个部分EditText
(大文件可能会很慢)。
有没有人知道我将如何做这件事?
我正在尝试用跨度替换Editable
返回的一部分。getText()
我已经尝试过getText().replace()
,但这仅适用于CharSequences
.
我尝试这样做的原因是我可以一个EditText
接一个地突出显示一个部分(经过一小段延迟),而不是遍历并突出显示整个部分EditText
(大文件可能会很慢)。
有没有人知道我将如何做这件事?
这个最小尺寸的例子使“first”这个词变大了:
public class SpanTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String dispStr = "I'm the first line\nI'm the second line";
TextView tv = (TextView) findViewById(R.id.textView1);
int startSpan = dispStr.indexOf("first");
int endSpan = dispStr.indexOf("line");
Spannable spanRange = new SpannableString(dispStr);
TextAppearanceSpan tas = new TextAppearanceSpan(this, android.R.style.TextAppearance_Large);
spanRange.setSpan(tas, startSpan, endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(spanRange);
}
}
您可以根据自己的需要进行调整
我最近回答了一个 smilar 问题:How to use SpannableString with Regex in android? . 但我会添加该答案的副本。
这是一个可以帮助你的课程:
public class Replacer {
private final CharSequence mSource;
private final CharSequence mReplacement;
private final Matcher mMatcher;
private int mAppendPosition;
private final boolean mIsSpannable;
public static CharSequence replace(CharSequence source, String regex,
CharSequence replacement) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
return new Replacer(source, matcher, replacement).doReplace();
}
private Replacer(CharSequence source, Matcher matcher,
CharSequence replacement) {
mSource = source;
mReplacement = replacement;
mMatcher = matcher;
mAppendPosition = 0;
mIsSpannable = replacement instanceof Spannable;
}
private CharSequence doReplace() {
SpannableStringBuilder buffer = new SpannableStringBuilder();
while (mMatcher.find()) {
appendReplacement(buffer);
}
return appendTail(buffer);
}
private void appendReplacement(SpannableStringBuilder buffer) {
buffer.append(mSource.subSequence(mAppendPosition, mMatcher.start()));
CharSequence replacement = mIsSpannable
? copyCharSequenceWithSpans(mReplacement)
: mReplacement;
buffer.append(replacement);
mAppendPosition = mMatcher.end();
}
public SpannableStringBuilder appendTail(SpannableStringBuilder buffer) {
buffer.append(mSource.subSequence(mAppendPosition, mSource.length()));
return buffer;
}
// This is a weird way of copying spans, but I don't know any better way.
private CharSequence copyCharSequenceWithSpans(CharSequence string) {
Parcel parcel = Parcel.obtain();
try {
TextUtils.writeToParcel(string, parcel, 0);
parcel.setDataPosition(0);
return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
} finally {
parcel.recycle();
}
}
}
以及一个使用示例:
CharSequence modifiedText = Replacer.replace("ABC aaa AB ABC aa ad ABC", "ABC",
Html.fromHtml("<font color=\"red\">CBA</font>"));
textView.setText(modifiedText);