13
1

More than 3 years have passed since last update.

Android: layout_marginHorizontal と paddingHorizontal は積極的に使おう

Last updated at Posted at 2020-07-26

結論

Android XML のレイアウトで左右に同じサイズの margin, padding を設定するときには、個別にパラメーターを設定するのではなく layout_marginHorizontal paddingHorizontal を使いましょう。

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingHorizontal="16dp">
...
</FrameLayout>

android:paddingHorizontal="16dp"android:paddingLeft="16dp"android:paddingRight="16dp" を指定したものと同じ意味となります。

上下の margin, padding の場合は layout_marginVertical paddingVertical を使います。

~Horizontal, ~Vertical は Android 8 未満でも使える

これらは Android 8 からサポートされた機能ですが、通常通りビルドするだけで Android 8 未満でも動作します。

Unified layout margins and padding

image.png

AAPT2 2.16 により、 ~Horizontal 要素が ~Left ~Right、 ~Vertical 要素が ~Top ~Bottom へ変換されるため、 Android 8 未満を含めたすべての Android バージョンで利用することができます。

Versioning of XML files is more intelligent, using a small set of rules to degrade specific newer attributes to backwards compatible versions of them. Ex: android:paddingHorizontal degrades to android:paddingLeft and android:paddingRight.

最新のビルド環境を使っていれば AAPT2 は上記に対応していると思います。 AAPT2 は Android SDK Build-Tools に含まれるため、最新の Build-Tools を使いましょう。

要素一覧

margin, padding それぞれ Horizontal と Vertical があります。

android:layout_marginHorizontal

Specifies extra space on the left and right sides of this view. Specifying layout_marginHorizontal is equivalent to specifying layout_marginLeft and layout_marginRight.

android:layout_marginVertical

Specifies extra space on the top and bottom sides of this view. Specifying layout_marginVertical is equivalent to specifying layout_marginTop and layout_marginBottom with that same value.

android:paddingHorizontal

Sets the padding, in pixels, of the left and right edges;

android:paddingVertical

Sets the padding, in pixels, of the top and bottom edges;

13
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
13
1