Like highlighting in bold or italics, or highlighting selected text in an Edittext program

I need to develop an application as a sticky note. The user enters the text in the Edittext, when I select the text, I will open a pop-up window to select an option, for example (BOLD, ITALIC, UNDERLINE). when the user selects the options, I need to change the selected text.

Does anyone go through this?

-1
source share
2 answers

Have you tried this?

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

If you find a way to popup options and how to get the selected option (Bold, Italic, 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 will work for you.

0
source

All Articles