6

我正在开发像记事本这样的应用程序,我想在其中动态更改选定的文本格式(颜色、更改字体样式、粗体、斜体、下划线等)。如何格式化特定单词?

4

2 回答 2

3

getSelectionStart()您可以使用and方法获取所选单词getSelectionEnd()

EditText etx=(EditText)findViewById(R.id.editext);

int startSelection=etx.getSelectionStart();
int endSelection=etx.getSelectionEnd();

String selectedText = etx.getText().substring(startSelection, endSelection);

然后,您可以在按钮单击/其他事件上将其带到SpannableStringBuilder后,通过在完整字符串中使用此选定子字符串来应用您的特定格式

格式化文本的代码:

  int startSelection=etx.getSelectionStart();
  int endSelection=etx.getSelectionEnd();

                  final SpannableStringBuilder sb = new SpannableStringBuilder(etx.getText().toString());

                        final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
                        final StyleSpan iss = new StyleSpan(android.graphics.Typeface.ITALIC); // Span to make text italic                                     
                        sb.setSpan(iss, startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                        sb.setSpan(bss, startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                        etx.setText(sb);    

参考

于 2012-05-18T09:30:16.790 回答
0
EditText et1=(EditText)findViewById(R.id.edit);

int startSelection=et.getSelectionStart();
int endSelection=et.getSelectionEnd();

String selectedText = et1.getText().substring(startSelection, endSelection);

希望此代码适合您的情况

于 2012-05-18T09:30:01.417 回答