如何在EditText中增加所选文本的大小?

时间:2015-11-26 20:32:00

标签: android android-edittext

在我的应用程序(一个诗人/引用编写应用程序)中,用户应该能够选择文本的一部分,并在每次增量时使其变大(+ 7.f)或更小(-7.f)按下/减量按钮。

我一直在尝试使用AbsoluteSizeSpan调整下面的代码(粗体当前选定的文字)来增加/减少文字大小:

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;

这是我尝试调整内联大小更改:

case R.id.incline:
    android.text.style.AbsoluteSizeSpan [] inclineSpan = str.getSpans(selectionStart, selectionEnd,   android.text.style.AbsoluteSizeSpan.class);

    str.setSpan(new android.text.style.AbsoluteSizeSpan(editText.setTextSize(TypedValue.COMPLEX_UNIT  _PX, editText.getTextSize() + 7.f)), selectionStart, selectionEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
    editText.setSelection(selectionStart, selectionEnd);
    break;

但是,此代码仅增加按下增量按钮的第一时间的所选文本大小,而我希望所选文本大小增加每个时间增量按钮被压了。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

我终于找到了一个完全符合我想要的解决方案,而且只有两行代码:

case R.id.incline:
    str.setSpan(new RelativeSizeSpan(1.1f), selectionStart, selectionEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
    editText.setSelection(selectionStart, selectionEnd);
    break;

重要的变化是应用RelativeSizeSpan(1.1f)类型的范围而不是类型AbsoluteSizeSpan的范围。鉴于AbsoluteSizeSpan根据EditText中的原始文字大小更改文字大小,RelativeSizeSpan会根据当前大小更改文字大小跨度中包含的每个字符!

答案 1 :(得分:1)

您正在使用getTextSize来增加字体大小,但AbsoluteSizeSpan不会更改textSize,只会更改范围内文本的大小。您将需要一个辅助变量来控制文本大小,如下所示:

//this should go in the initialization of your view
float spanTextSize = editText.getTextSize();

此处您的案例已更新:

case R.id.incline:
            spanTextSize += 7.f;
            android.text.style.AbsoluteSizeSpan [] inclineSpan =   str.getSpans(selectionStart, selectionEnd,   android.text.style.AbsoluteSizeSpan.class);

            str.setSpan(new android.text.style.AbsoluteSizeSpan(editText.setTextSize(TypedValue.COMPLEX_UNIT  _PX, spanTextSize)), selectionStart, selectionEnd,   Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            editText.setSelection(selectionStart, selectionEnd);
            break;