24

TextViewデバイスの DPI/画面解像度に依存する最大高さが不明です。したがって、たとえば、MDPI デバイスでは、この最大の高さにより、一度に 2 行しか表示できず、この値は未定義の数まで増やすことができます。

私の問題は、楕円サイズ機能に関連しています。あるデバイスで 4 行を表示できるとします。このように最大行数を手動で設定すると...

<TextView
    android:id="@+id/some_id"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:ellipsize="end" 
    android:maxLines="4"
    android:singleLine="false"
    android:layout_weight="1"
    android:gravity="center_vertical"
    android:text="This is some really really really really really long text"
    android:textSize="15sp" />

...すべて正常に動作します。テキストが適切に収まらない場合は、次のように 4 行目の末尾に省略記号が追加されます。

This is some
really really
really really
really long...

ただし、DPI と画面解像度の任意の組み合わせのサポートを含めたいので、行数を静的変数として設定したくはありません。したがってmaxLines、省略記号を削除すると、4 行目に正しく表示されなくなり、代わりにテキストの不完全な部分が表示されます。

This is some
really really
really really
really long

サイズをわずかに大きくするTextViewと、残りのテキストがまだ他の の「後ろ」に描画されていることがわかりますViews。変数の設定もmaxHeight機能していないようです。

この問題の解決策が本当に見つからないようです。何か案は?それが役立つ場合、私は Android v4.0.3 以降 (API レベル 15) でのみ作業しています。

4

2 に答える 2

37

TextViewwithTextView#getHeight()とに収まる行数を計算しますTextView#getLineHeight()。次に、 を呼び出しますTextView#setMaxLines()

ViewTreeObserver observer = textView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int maxLines = (int) textView.getHeight()
                / textView.getLineHeight();
        textView.setMaxLines(maxLines);
        textView.getViewTreeObserver().removeGlobalOnLayoutListener(
                this);
    }
});
于 2013-01-05T19:09:10.767 に答える