Percent Support Libraryを使ってレイアウトを%指定する


Percent Support Libraryはdeprecatedになりました。

タブレット対応で画面サイズに併せて引き伸ばしたかったので使ってみた

準備

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

書き方

下記のような感じで android:layout_width の代わりに app:layout_widthPercent が使える
android:じゃなくてapp:なので間違えると死ぬ
※ app:部分は任意の文字列が使えますがxmlns:で定義した名前空間と合ってないと死にます

<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        app:layout_widthPercent="80%"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true">
    </RelativeLayout>
</android.support.percent.PercentRelativeLayout>

だいたいこんな感じ

属性名 役割
layout_widthPercent 要素の横幅を%指定する
layout_heightPercent 要素の高さを%指定する
layout_marginPercent マージンを%指定する
layout_marginLeftPercent 左側のマージンを%指定する
layout_marginTopPercent 上側のマージンを%指定する
layout_marginRightPercent 右側のマージンを%指定する
layout_marginBottomPercent 下側のマージンを%指定する
layout_marginStartPercent 左(RTL環境では右)からのマージンを%指定する
layout_marginEndPercent 右(RTL環境では左)からのマージンを%指定する
layout_aspectRatio アスペクト比を維持したまま%指定する

詳細はAndroid Developerのページを確認しよう

追記: xml側の%指定

dimens.xml
<dimen name="hoge">80%</dimen>

とかやってるとエラー吐いてビルド出来ないので

dimens.xml
<item name="hoge" type="dimen">80%</dimen>

とする