LoginSignup
13

More than 5 years have passed since last update.

android:gravity="right"で右端によらなかった問題

Last updated at Posted at 2015-05-01

ぱっとみしょうもないことでつまづいたので、記事にしてみました

androidのUIの実装でTextViewをよしなに配置しようとandroid:gravityを使おうとしたところ、
右によること無く左寄せで配置された("ほげほげ"は左寄せ、"削除"は右寄せにしたい)。

スクリーンショット 2015-05-01 11.13.58.png

コードはこんな感じです。

       <LinearLayout
            android:orientation="horizontal"
            android:layout_width="320dp"
            android:layout_height="30dp">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"
                android:text="ほげほげ"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:textColor="#ffffff"
                android:text="削除" />

        </LinearLayout>

結論から行ってしまうとandroid:width="wrap_content"で指定していたのが原因。
これを"fill_parent"に直すとうまくいった。

スクリーンショット 2015-05-01 11.13.20.png

理由としてはwrap_contentだとTextViewは文字の大きさ分の領域しか認識しないため、gravityで文字そのものの位置を決める空間(?)が存在しないので右寄せが適用されなかった。

スクリーンショット 2015-05-01 11.21.55.png

しかし、fill_contentにすると、TextViewが認識する領域は親コンテンツの横幅すべての範囲を認識するため右寄せが可能になるようだ。

スクリーンショット 2015-05-01 11.23.37.png

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
13