public class TextTypeOption {
public final static int BOLD = 1;
public final static int ITALIC = 2;
public final static int UNDERLINE = 3;
public TextTypeOption(int option) {
this.option = option;
}
public int getOption() {
return this.option
}
public boolean isBold() {
return option == BOLD;
}
public boolean isItalic() {
return option == ITALIC;
}
public boolean isUnderline() {
return option == UNDERLINE;
}
}
定义一个 TextTypeOption 值:
TextTypeOption option = new TextTypeOption(TextTypeOption.BOLD);//为粗体
1) 使用Html.fromText(String text)
if(option.isBold()) {
text = text.replace(selectedText , "<b>"+ (selectedText + "</b>");
et.setText(Html.fromHtml(text));
}
if(option.isItalic()) {
text = text.replace(selectedText , "<i>"+ (selectedText + "</i>");
et.setText(Html.fromHtml(text));
}
if(option.isUnderline()) {
text = text.replace(selectedText , "<u>"+ (selectedText + "</u>");
et.setText(Html.fromHtml(text));
}
2) 使用Spannable
SpannableString span = new SpannableString(text);
if(option.isUnderline()) {
span.setSpan(new UnderlineSpan(),startSelection, endSelection , 0);
}
if(option.isBold()) {
span.setSpan(new StyleSpan(Typeface.BOLD), startSelection, endSelection , 0);
}
if(option.isItalic()) {
span.setSpan(new StyleSpan(Typeface.ITALIC), startSelection, endSelection , 0);
}
et.setText(span, TextView.BufferType.SPANNABLE);
附:我认为这不是优雅的方式,但它确实有效。