gpt4 book ai didi

android - 如何清除 EditText 的格式?

转载 作者:行者123 更新时间:2023-11-29 16:06:10 25 4
gpt4 key购买 nike

我有一个 EditText,可以添加粗体、斜体等格式....但我怎样才能删除它?我已经研究过 getSpans、过滤器和其他非字符串的东西,但无法理解它们!理想情况下,我希望能够清除特定标签以及围绕所选文本设置的所有标签。

更新我的解决方案:

private String getSelectedText(){
int start = Math.max(mText.getSelectionStart(), 0);
int end = Math.max(mText.getSelectionEnd(), 0);
return mText.getText().toString().substring(Math.min(start, end), Math.max(start, end));
}
private void clearFormat(){
int s1 = Math.max(mText.getSelectionStart(), 0);
int s2 = Math.max(mText.getSelectionEnd(), 0);
String text = getSelectedText(); if(text==""){ return; }
EditText prose = mText;
Spannable raw = new SpannableString(prose.getText());
CharacterStyle[] spans = raw.getSpans(s1, s2, CharacterStyle.class);
for (CharacterStyle span : spans) {
raw.removeSpan(span);
}
prose.setText(raw);
//Re-select
mText.setSelection(Math.min(s1,s2), Math.max(s1, s2));
}

最佳答案

but how can I remove it?

Spannable 上调用 removeSpan()

例如,这个方法来自this sample projectTextView 的内容中搜索搜索字符串并为其分配背景颜色,但前提是移除所有先前的背景颜色:

private void searchFor(String text) {
TextView prose=(TextView)findViewById(R.id.prose);
Spannable raw=new SpannableString(prose.getText());
BackgroundColorSpan[] spans=raw.getSpans(0,
raw.length(),
BackgroundColorSpan.class);

for (BackgroundColorSpan span : spans) {
raw.removeSpan(span);
}

int index=TextUtils.indexOf(raw, text);

while (index >= 0) {
raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
+ text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
index=TextUtils.indexOf(raw, text, index + text.length());
}

prose.setText(raw);
}
}

关于android - 如何清除 EditText 的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18157050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com