2012年5月6日日曜日

TextView#getLineCountメソッドの戻値がゼロ

TextView#getLineCountメソッドの戻値がゼロ

TextView#getLineCountメソッドの戻値がゼロになった。
android developersのTextViewには、getLineCountメソッドについて次の解説がある。
Return the number of lines of text, or 0 if the internal Layout has not been built.
internal Layoutが構築されていないことが原因である、ということだ。
TextViewが表示されない状況下でTextViewを生成した場合に「戻値ゼロ」になってしまうようであるが、詳細は不明である。

なお、私が遭遇した事例では、一旦この「戻値ゼロ」が発生すると、当該TextViewが画面に表示された後であっても、この 「戻値ゼロ」 は発生し続けた。

調査した結果、原因はTextViewを定義したxmlにあった。

 「戻値ゼロ」 が発生するxmlファイル
<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/app_name"
    >
</TextView>

 「戻値ゼロ」 が発生しないxmlファイル
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        >
    </TextView>
</LinearLayout>

TextViewの外側をLinearLayoutで囲ってやれば良い。

また、Javaのcodeにおいて、TextViewを単体でnewした場合にも発生する。例えば、次のように。
TextView tv = new TextView(this);
おそらく、このJava codeにおいても、TextViewの外側をLinearLayoutで囲うようにすれば良いだろう。

internal Layoutの構築と、TextViewを単体で生成することとの因果関係については、私には分からない。むむむ!

0 件のコメント:

コメントを投稿