如何以编程方式在Edittext中以粗体或斜体显示或在选定文本下划线 [英] How to bold or italic or underline the selected text in Edittext programatically

查看:189
本文介绍了如何以编程方式在Edittext中以粗体或斜体显示或在选定文本下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须开发一个便签之类的应用程序.用户在Edittext中输入文本,同时选择文本,我将打开弹出窗口以选择(BOLD,ITALIC,UNDERLINE)之类的选项.当用户选择选项时,我需要更改选定的文本.

I have to develop an App like sticky note. User enter the text in Edittext, while selecting the text I will open the popup to select the option like (BOLD,ITALIC,UNDERLINE). when user select the options i need to change the selected text..

有人通过吗?

推荐答案

如果您找到了一种弹出选项以及如何检索所选选项(粗体,斜体,下划线)的方法,然后使用此方法设置文本格式

If you have found a way the popup the options and how to retrieve the selected option(Bold, Italics, Underline), Then use this to format the text

private void formatText(EditText editText) {
    int end = editText.length();

    //get the selected text position as integer
    start = editText.getSelectionStart();
    stop = editText.getSelectionEnd();
    //check if the user started the selection from the left or the right
    if (start > stop) {
        stop = editText.getSelectionStart();
        start = editText.getSelectionEnd();
    }

        //gets the texts as html incase if previous formatting exists
    String textBefore = Html.toHtml(new SpannableString(text.getText().subSequence(0, start)));
    String selectedText = Html.toHtml(new SpannableString(text.getText().subSequence(start, stop)));
    String textAfter = Html.toHtml(new SpannableString(text.getText().subSequence(stop, end)));
    //Check if the selected text is empty ie if the did not select anything
    if (!selectedText.equals("") || start != stop) {
       //format the text
       String formatted = "<b>" + selectedText + "</b>";
       //build back the text
        StringBuilder builder = new StringBuilder();
        builder.append(textBefore);
        builder.append(Html.toHtml(formatted));
        builder.append(textAfter);

        editText.setText(Html.fromHtml(builder.toString()));
        //make the cursor stay after the selected text
        //you can also make the selected text selected here
        editText.setSelection(stop); 
        //clear your local variables
        textbefore = "";
        textafter = "";
        selectedText = "";
    }
    else {
        //you can also use snack bar here
        Toast.makeText(context, "select a text", Toast.LENGTH_SHORT).show();
    }
}

我认为这应该对您有用

这篇关于如何以编程方式在Edittext中以粗体或斜体显示或在选定文本下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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