15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

レイアウトの余白を埋める

Posted at

余白を埋める

開発中、ViewとViewの間に余白を設けたい場合があります。
通常はmargindividerで調整しますが、間に余白のためのViewを置く場合もあると思います。
実はAndroidには、余白調整のためのSpaceというViewが存在しているのです。

Space

SpaceはApi level 14で追加されたGridLayoutで発生する空のカラムを表現するために作られました。
Support Library v7にGridLayoutが収録された際、Spaceも同時に収録されました。

Spaceと他のViewとの大きな違いとして、描画を行わないという特徴があります。
以下のコードはSpace#drawメソッドの実装になります。

    /**
     * Draw nothing.
     *
     * @param canvas an unused parameter.
     */
    @Override
    public void draw(Canvas canvas) {
    }

Draw nothingの言葉通り、Spaceでは背景色を含む一切の描画が行われません
余白のみ背景色を変えたいという場合には使えませんが、Viewの中で最も描画負荷が少ないというメリットがあります。

実装

Gradleの場合、以下のようにgridlayout-v7ライブラリを取り込みます。

compile 'com.android.support:gridlayout-v7:20.0.+'

例として、縦に並んだカニ画像の間に50dpの余白を設けてみます。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    android:orientation="vertical">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/kani" />

    <android.support.v7.widget.Space
        android:layout_width="match_parent"
        android:layout_height="50dp" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/kani" />

</LinearLayout>

layout-2014-08-21-195827_convert_20140821201849.png

こうなりました。
余白部分はLinearLayoutの背景が透過されています。

注意点

繰り返しになりますが、Spaceに背景色を設定しても無視されます。
以下のような記述はできますが、描画には反映されません。

    <android.support.v7.widget.Space
        android:layout_width="match_parent"
        android:background="@android:color/white"
        android:layout_height="50dp" />

使いどころ

正直、GridLayout以外で使える場面はあまりないと思います。
大抵はmargindividerで十分です。
しかし、どうしても余白のためにViewを配置したい場合Spaceの存在を思い出してください。

15
15
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
15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?