用户在 edittext 本身中键入时应该能够创建如下内容。
“这段文字是粗体,这是斜体。”
我不希望整个文本采用任何一种格式(即粗体/斜体/下划线)。
谢谢。
最佳答案
这是可以帮助您的解决方案..首先获取编辑文本的选定数据(单击粗体/斜体/下划线按钮):
EditText et=(EditText)findViewById(R.id.edit);
String text = et.getText();
int startSelection=et.getSelectionStart();
int endSelection=et.getSelectionEnd();
String selectedText = et.getText().toString().substring(startSelection, endSelection);
在编辑文本中设置样式有两种方法:[这里选项检查是点击的按钮]
1) 使用html
if(option.bold)
{
text = text.replace(selectedText , "<b>"+ (selectedText + "</b>");
et.setText(Html.fromHtml(text));
}
if(option.italic)
{
text = text.replace(selectedText , "<i>"+ (selectedText + "</i>");
et.setText(Html.fromHtml(text));
}
if(option.underline)
{
text = text.replace(selectedText , "<u>"+ (selectedText + "</u>");
et.setText(Html.fromHtml(text));
}
2)使用Spannable
SpannableString span = new SpannableString(text);
if(option.underline)
{
span.setSpan(new UnderlineSpan(),startSelection, endSelection , 0);
}
if(option.bold)
{
span.setSpan(new StyleSpan(Typeface.BOLD), startSelection, endSelection , 0);
}
if(option.italic)
{
span.setSpan(new StyleSpan(Typeface.ITALIC), startSelection, endSelection , 0);
}
et.setText(span, TextView.BufferType.SPANNABLE);
关于android - 在 EditText 中键入文本时如何提供简单的测试编辑工具(粗体、斜体、下划线)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21722632/