8

最終的にはインデントがぶら下がっている一連のTextViewに興味があります。CSSを介してこれを行う標準的な方法は、マージンをXピクセルに設定してから、テキストのインデントを-Xピクセルに設定することです。明らかに、最初は「android:layout_marginLeft = "Xdp」で実行できますが、TextViewに-Xピクセルを適用する方法がわかりません。アイデアや回避策はありますか?提案をいただければ幸いです。

4

1 に答える 1

13

自分のプロジェクトでぶら下げインデントを機能させる方法を考え出しました。基本的に、android.text.style.LeadingMarginSpanを使用し、コードを介してテキストに適用する必要があります。LeadingMarginSpan.Standardは、完全インデント(1 param)またはハンギングインデント(2 params)コンストラクターのいずれかを取り、スタイルを適用するサブストリングごとに新しいSpanオブジェクトを作成する必要があります。TextView自体も、BufferTypeをSPANNABLEに設定する必要があります。

これを複数回行う必要がある場合、またはスタイルにインデントを組み込みたい場合は、カスタムインデント属性を取り、スパンを自動的に適用するTextViewのサブクラスを作成してみてください。静的に型付けされたブログのこのカスタムビューとXML属性のチュートリアル、およびXMLを使用したカスタムAndroidUI要素の宣言に関するSOの質問から多くのことを学びました。

TextViewの場合:

// 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 に答える