我有兴趣拥有一系列 TextView,最终带有悬挂缩进。通过 CSS 执行此操作的标准方法是将边距设置为 X 像素,然后将文本缩进设置为 -X 像素。显然,我可以用“android:layout_marginLeft="Xdp" 来做第一个,但我不确定如何在 TextView 上施加 -X 像素。有什么想法或解决方法吗?我很感激任何建议。
4557 次
1 回答
13
想出了如何使悬挂缩进适用于我自己的项目。基本上您需要使用 android.text.style.LeadingMarginSpan,并通过代码将其应用于您的文本。LeadingMarginSpan.Standard 采用完整缩进(1 个参数)或悬挂缩进(2 个参数)构造函数,您需要为要应用样式的每个子字符串创建一个新的 Span 对象。TextView 本身也需要将其 BufferType 设置为 SPANNABLE。
如果您必须多次执行此操作,或者想要在您的样式中合并缩进,请尝试创建一个 TextView 的子类,该子类采用自定义缩进属性并自动应用跨度。我从静态类型博客的自定义视图和 XML 属性教程和 SO 问题Declaring a custom android UI element using XML中得到了很多用处。
在文本视图中:
// android.text.style.CharacterStyle is a basic interface, you can try the
// TextAppearanceSpan class to pull from an existing style/theme in XML
CharacterStyle style_char =
new TextAppearanceSpan (getContext(), styleId);
float textSize = style_char.getTextSize();
// indentF roughly corresponds to ems in dp after accounting for
// system/base font scaling, you'll need to tweak it
float indentF = 1.0f;
int indent = (int) indentF;
if (textSize > 0) {
indent = (int) indentF * textSize;
}
// android.text.style.ParagraphStyle is a basic interface, but
// LeadingMarginSpan handles indents/margins
// If you're API8+, there's also LeadingMarginSpan2, which lets you
// specify how many lines to count as "first line hanging"
ParagraphStyle style_para = new LeadingMarginSpan.Standard (indent);
String unstyledSource = this.getText();
// SpannableString has mutable markup, with fixed text
// SpannableStringBuilder has mutable markup and mutable text
SpannableString styledSource = new SpannableString (unstyledSource);
styledSource.setSpan (style_char, 0, styledSource.length(),
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
styledSource.setSpan (style_para, 0, styledSource.length(),
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
// *or* you can use Spanned.SPAN_PARAGRAPH for style_para, but check
// the docs for usage
this.setText (styledSource, BufferType.SPANNABLE);
于 2012-05-31T18:31:16.743 回答