PercentSupportLibrary使ってみた

ブログを作ってからずっと書いていませんでしたがこれからはちゃんと書いて行きます。

PercentSupportLibraryとは

よくCSSとかでwidth: 100%的なことをする気がしますが、Androidのlayoutでもそれを可能にしたSupport Libraryです(てきとう。

Androidで割合を上のような割合でlayoutを表現する場合LinearLayoutのweightを使うかと思いますが、今回はFrameLayoutとRelativeLayoutでそれがpercentつかえるようになったよ!的な内容です。他にも良い所があると思うのですが、よくわかってないので誰か指摘していただきたいです。

にわか程度に使ってみたので軽く紹介したいと思います。

開発環境はAndroidStudio(v1.3.2)を使用しています。

使い方

build.gradleに以下を追加してください。

dependencies {
    compile 'com.android.support:percent:23.0.0'
}

Percent LayoutではPercentFrameLayoutPercentRelativeLayoutがあります。

今回はPercentRelativeLayoutだけ紹介したいと思います。

使い方は簡単で以下の様な感じです。

<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Title"/>

    <ImageView
        android:id="@+id/image"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_below="@id/text"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher"
        app:layout_widthPercent="80%"
        app:layout_heightPercent="50%"/>

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/image"
        android:layout_centerHorizontal="true"
        android:text="Submit"
        app:layout_widthPercent="70%"/>


</android.support.percent.PercentRelativeLayout>

↑の例は例とは言えない気がしますが、割合を100%に抑えれば端末によってlayoutがksになるなんてことはなくなるという感じです。

実際に動かすとこんな感じになります。

f:id:ksfee:20150915185726p:plain

まとめ

RelativeLayoutで割合が使えるとかなりlayoutのバリエーションが広がる気がするのでこれからがっつり使っていけたらと思います。

この間のインターンに言った時に初めて使ったんですがかなり良いです。

あ、インターンの記事は後で書きます。

参考URL