切换编辑文本字体

时间:2015-09-10 21:46:09

标签: android android-edittext spannable

Hello Everyone我正在创建一个应用程序,用户可以在单击按钮时将斜体文本设置为斜体。

// Captures Contextual Menu Clicks//
public void onContextualMenuItemClicked(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.bold) {
        // do some stuff
    }

    if (id == R.id.italic) {

        int startSelection = noteContent.getSelectionStart();
        int endSelection = noteContent.getSelectionEnd();
        Spannable spannable = noteContent.getText();

        spannable.setSpan(new StyleSpan(Typeface.ITALIC) , startSelection , endSelection , 0);



        StyleSpanRemover spanRemover = new StyleSpanRemover();

        spanRemover.RemoveStyle(spannable,startSelection,endSelection,Typeface.ITALIC);
    }

此代码使其成斜体

        int startSelection = noteContent.getSelectionStart();
        int endSelection = noteContent.getSelectionEnd();
        Spannable spannable = noteContent.getText();

        spannable.setSpan(new StyleSpan(Typeface.ITALIC) , startSelection , endSelection , 0);

这使它成为非斜体

        StyleSpanRemover spanRemover = new StyleSpanRemover();

        spanRemover.RemoveStyle(spannable,startSelection,endSelection,Typeface.ITALIC

我希望用户单击相同的按钮以使其显示为斜体和非斜体。如果我可以使用语句来获得可以选择的单词的TypeFace,该怎么办?这样它就知道是否斜体

更新:这就是我现在所拥有的

     int startSelection = noteContent.getSelectionStart();
        int endSelection = noteContent.getSelectionEnd();
        Spannable spannable = noteContent.getText();

        StyleSpan[] spans = spannable.getSpans(startSelection, endSelection, StyleSpan.class);

        if (spans.length == 0) {

            spannable.setSpan(new StyleSpan(Typeface.ITALIC), startSelection, endSelection , 0);

        } else {

            spannable.setSpan(new StyleSpan(Typeface.NORMAL), startSelection, endSelection , 0);
        }

即使代码运行代码

  spannable.setSpan(new StyleSpan(Typeface.NORMAL), startSelection, endSelection , 0);

并将其恢复正常。但是它不会将spans.length设置回零,所以我不能再将它设置为如何将spans.length设置为零。

1 个答案:

答案 0 :(得分:0)

您可以使用getSpans(startSelection, endSelection, StyleSpan.class)查看选择范围中存在的跨距。基于此,您可以决定是否(以及如何)使文本斜体化。请注意,用户可能会突出显示包含 正常文本和斜体文本的部分。

修改

StyleSpan[] spans = spannable.getSpans(startSelection, endSelection, StyleSpan.class);
if (spans.length == 0) {
    // no spans, italicize text here
} else {
    // TODO
}