繁体   English   中英

如何设置选中的文字为粗体?

[英]how to set selected Text bold?

我想以EditText粗体设置选定的文本。

已经可以找出我选择了哪些字符,并通过getSelectionStart() and getSelectionEnd( )知道位置在哪里。

但是我的问题是,我想用按钮将选定的文本设置为粗体,而不知道如何用字符串设置字体为粗体(我只知道如何使用EditText进行设置)。

所以这是我的示例代码:

    fettdruckButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            int selectionStart = fullscreenEdittext.getSelectionStart();
            int selectionEnd = fullscreenEdittext.getSelectionEnd();

            int differenz = selectionEnd - selectionStart;

            String selectedText = fullscreenEdittext.getText().toString().substring(selectionStart, selectionEnd);
            Log.d("selectedText", "selectedText " + selectedText + "|" + selectionStart + "|" + selectionEnd);


            //fullscreenEdittext.setTypeface(null, Typeface.BOLD);

        }
    });

使用SpannableStringBuilder。

SpannableStringBuilder stringBuilder = (SpannableStringBuilder) fullscreeneditText.getText();
stringBuilder.setSpan(new StyleSpan(Typeface.BOLD), selectionStart, selectionEnd, 0);

请注意,如果要多次执行此操作,则应先删除原始跨度。

使用Editext的属性fullscreenEdittext.setText(Html.fromHtml(styledText)); 使用html格式标记<b>selectedText</b>使选定的文本变为粗体。 请看下面的代码片段

int selectionStart = fullscreenEdittext.getSelectionStart();
    int selectionEnd = fullscreenEdittext.getSelectionEnd();

    String startingText = fullscreenEdittext.getText().toString()
            .substring(0, selectionStart);
    String selectedText = fullscreenEdittext.getText().toString()
            .substring(selectionStart, selectionEnd);
    String endingText = fullscreenEdittext.getText().toString()
            .substring(selectionEnd);

    fullscreenEdittext.setText(Html.fromHtml(startingText + "<b>"
            + selectedText + "</b>" + endingText));
String completetext=fullscreenEdittext.getText().toString();
int selectionStart = fullscreenEdittext.getSelectionStart();
int selectionEnd = fullscreenEdittext.getSelectionEnd();
int differenz = selectionEnd - selectionStart;
String selectedText = fullscreenEdittext.getText().toString().substring(selectionStart, selectionEnd);
Log.d("selectedText", "selectedText " + selectedText + "|" + selectionStart + "|" + selectionEnd);

String part1=fullscreenEdittext.getText().toString().substring(0, selectionStart);

String part2=fullscreenEdittext.getText().toString().substring(selectionStart, selectionEnd);

String part3=fullscreenEdittext.getText().toString().substring(selectionEnd,completetext.length() );

fullscreenEdittext.setText(Html.fromHtml(part1+"<b>" + part2+ "</b>" +part3));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM