How to bold or italic or underline the selected text in Edittext programatically

别等时光非礼了梦想. 提交于 2019-12-12 09:26:08

问题


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

Does anyone go through this?


回答1:


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

I think this should work for you




回答2:


Did you tried that?

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


来源:https://stackoverflow.com/questions/37002177/how-to-bold-or-italic-or-underline-the-selected-text-in-edittext-programatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!