有没有办法在Android TextView中格式化<BlockQuote>
HTML标记?如果我可以使用图像,广告和多个垂直滚动页面轻松操作3列,则可以选择WebView。
文本视图显然处理标记,我得到一条丑陋的蓝线来表示blockquote。有没有办法改变线条的颜色或更好地提供我自己的线条图像?
答案 0 :(得分:19)
如果您使用android.text.Html#fromHtml
来构建android.text.Spannable
,则blockquote
将通过android.text.style.QuoteSpan
实施。这个QuoteSpan
不允许配置。
最简单的解决方案是搜索QuoteSpan
中的所有Spannable
并替换它们:
private void replaceQuoteSpans(Spannable spannable) {
QuoteSpan[] quoteSpans = spannable.getSpans(0, spanned.length(), QuoteSpan.class);
for (QuoteSpan quoteSpan : quoteSpans) {
int start = spannable.getSpanStart(quoteSpan);
int end = spannable.getSpanEnd(quoteSpan);
int flags = spannable.getSpanFlags(quoteSpan);
spannable.removeSpan(quoteSpan);
spannable.setSpan(new CustomQuoteSpan(
MY_BACKGROUND_COLOR,
MY_STRIPE_COLOR,
MY_STRIPE_WIDTH,
MY_GAP_WIDTH),
start,
end,
flags);
}
}
使用CustomQuoteSpan
类,如:
/**
* android.text.style.QuoteSpan hard-codes the strip color and gap. :(
*/
public class CustomQuoteSpan implements LeadingMarginSpan, LineBackgroundSpan {
private final int backgroundColor;
private final int stripeColor;
private final float stripeWidth;
private final float gap;
public CustomQuoteSpan(int backgroundColor, int stripeColor, float stripeWidth, float gap) {
this.backgroundColor = backgroundColor;
this.stripeColor = stripeColor;
this.stripeWidth = stripeWidth;
this.gap = gap;
}
@Override
public int getLeadingMargin(boolean first) {
return (int) (stripeWidth + gap);
}
@Override
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
CharSequence text, int start, int end, boolean first, Layout layout) {
Paint.Style style = p.getStyle();
int paintColor = p.getColor();
p.setStyle(Paint.Style.FILL);
p.setColor(stripeColor);
c.drawRect(x, top, x + dir * stripeWidth, bottom, p);
p.setStyle(style);
p.setColor(paintColor);
}
@Override
public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int lnum) {
int paintColor = p.getColor();
p.setColor(backgroundColor);
c.drawRect(left, top, right, bottom, p);
p.setColor(paintColor);
}
}