Edittext

时间:2015-11-18 19:35:42

标签: android

对于我的Edittext,我正在为用户创建一个选项,以便能够将所选文本设置为粗体,但用户也应该能够再次“解开”相同的文本。

此功能还包括斜体,下划线和笔划,但稍后会添加。

使文本粗体的代码有效,但我不知道如何解开所选文本或如何检查文本是否已经是粗体。

  CharacterStyle cs;
    int start = editText.getSelectionStart();
    int end = editText.getSelectionEnd();
    SpannableStringBuilder ssb = new    SpannableStringBuilder(editText.getText());

    switch(item.getItemId()) {

        case R.id.bold:


            cs = new StyleSpan(Typeface.BOLD);
            ssb.setSpan(cs, start, end, 1);
            editText.setText(ssb);
            return true;

2 个答案:

答案 0 :(得分:1)

已在网络上找到此算法:https://code.google.com/archive/p/droid-writer/

int selectionStart = editText.getSelectionStart();
int selectionEnd = editText.getSelectionEnd();

if (selectionStart > selectionEnd) {
        int temp = selectionEnd;
        selectionEnd = selectionStart;
        selectionStart = temp;
    }


    if (selectionEnd > selectionStart) {
        Spannable str = editText.getText();
        boolean exists = false;
        StyleSpan[] styleSpans;

        switch (item.getItemId()) {
            case R.id.bold:
                styleSpans = str.getSpans(selectionStart, selectionEnd, StyleSpan.class);

                // If the selected text-part already has BOLD style on it, then
                // we need to disable it
                for (int i = 0; i < styleSpans.length; i++) {
                    if (styleSpans[i].getStyle() == android.graphics.Typeface.BOLD) {
                        str.removeSpan(styleSpans[i]);
                        exists = true;
                    }
                }

                // Else we set BOLD style on it
                if (!exists) {
                    str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), selectionStart, selectionEnd,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                }

                editText.setSelection(selectionStart, selectionEnd);
                break;

答案 1 :(得分:0)

相应地使用,下面的代码比你的更容易实现。

textView.setTypeface(null, Typeface.NORMAL);
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);

为了将指定文本设置为粗体,我发现使用Html构建字符串要容易得多。例如,如果您希望某些文本看起来像这样

  

1111 neil

您可以使用以下方式执行此操作:

String sourceString = "<b>" + id + "</b> " + name; 
mytextview.setText(Html.fromHtml(sourceString));