如何使用粗体或斜体或以编程方式在编辑文本中为选定的文本加下划线

时间:2016-05-03 10:53:33

标签: android android-edittext bold

我必须像粘滞便笺一样开发App。用户在Edittext中输入文本,同时选择文本我将打开弹出窗口以选择像(BOLD,ITALIC,UNDERLINE)这样的选项。当用户选择我需要更改所选文本的选项时..

有没有人经历过这个?

3 个答案:

答案 0 :(得分:1)

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

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

我认为这应该对你有用

答案 1 :(得分:0)

你试过那个吗?

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

答案 2 :(得分:0)

科特林

更改Typeface.BOLDTypeface.ITALICUnderlineSpan()

val spannableString: Spannable = SpannableStringBuilder(editText.text)
        spannableString.setSpan(
        StyleSpan(Typeface.BOLD),
            editText.selectionStart,
            editText.selectionEnd,
            0
        )
editText.setText(spannableString)