我正在开发一个像记事本这样的应用程序,我想在其中动态更改所选的文本格式(颜色,更改字体样式,粗体,斜体,下划线等) 如何格式化特定单词?
答案 0 :(得分:3)
您可以使用getSelectionStart()
和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);
答案 1 :(得分:0)
EditText et1=(EditText)findViewById(R.id.edit);
int startSelection=et.getSelectionStart();
int endSelection=et.getSelectionEnd();
String selectedText = et1.getText().substring(startSelection, endSelection);
希望此代码适合您的情况