LoginSignup
1
1

More than 5 years have passed since last update.

AndroidアプリでTableRow内のlayout_widthが効かない場合がある

Posted at

TableRow内のビューに対してlayout_gravityを指定するとlayout_widthの設定がうまく効かない場合がありました。
LinearLayoutなどで同様にしてもlayout_widthはちゃんと効きます。

ActivityのXMLを以下のようにすると、

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <TableRow>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TableRow" />
        <EditText
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_gravity="end" />
    </TableRow>
    <LinearLayout>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LinearLayout" />
        <EditText
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_gravity="end" />
    </LinearLayout>
</TableLayout>

実行したときにこのようになります。
tablelayoutcap.png

EditTextの中身は同じですが、TableRowのほうのEditTextはとても短いです・・。
(hintなどを入れると文字数分の長さになるので、layout_width="wrap_content"を指定したときのような動きになっていそうです)


なぜこうなるのかはよくわかりませんでしたが・・
TableRow内のビューにlayout_widthを設定しつつ右寄せしたい場合などは、ビューをLayoutで囲んで、Layoutに対してlayout_gravityを指定するとうまくいくようです。

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <TableRow>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TableRow" />
        <LinearLayout
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_gravity="end" >
            <EditText
                android:layout_width="100dp"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </TableRow>
</TableLayout>

tablelayoutcap2.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1