android - 在 EditText 中键入文本时如何提供简单的测试编辑工具(粗体、斜体、下划线)?

标签 android android-edittext rich-text-editor

用户在 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/

相关文章:

c# - 创建富文本模板

javascript - 在 WYSIHTML5 中禁用键盘按键

android - 如何编写具有深度导航的 Android 多 Pane 应用程序

android - locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) 使用 Wi-Fi 总是返回 false

Android EditText 不是多行

Android 问题 : EditText, KeyListener 和物理后退按钮

android - 这个错误是什么意思 ? (安卓)

android - 如何将 GraphView 集成到我的项目中?

android - TextInputLayout 中的输入类型文本密码

android - 在 Android 中创建一个简单的文本编辑器