如何清除EditText的格式? [英] How to clear formatting from an EditText?

查看:134
本文介绍了如何清除EditText的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 EditText ,并且可以添加粗体,斜体等格式.但是如何删除呢?我已经研究过getSpans,过滤器和其他非字符串内容,但无法理解它们!理想情况下,我希望能够清除特定标签以及所选文本周围设置的所有标签.

I have an EditText, and can add formatting such as bold, italic....but how can I remove it? I've looked into getSpans, filters, and other non-string things and haven't been able to make sense of them! Ideally, I'd like to be able to clear specific tags and all tags set around the selected text.

更新我的解决方案:

Update with my solution:

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().

例如,此方法来自此示例项目搜索在 TextView 的内容中搜索字符串并为其分配背景色,但前提是先删除所有先前的背景色:

For example, this method from this sample project searches for a search string in the contents of a TextView and assigns it a background color, but only after removing any previous background colors:

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

这篇关于如何清除EditText的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆