前書き
AndroidのUIを作る時に、スマホでは画面のこれぐらいの割合で表示したいけど、タブレットの時は別の割合で表示したい、という場面があるかと思います。
今回はその実装をするまでに行った過程を紹介したいと思います。
やりたいこと
例として、スマホの場合はボタン1を40%、ボタン2を60%、
タブレットの場合はボタン1を10%、ボタン2を90%の縦幅で表示したいとします。
dimenでうまくやろうとしてみた
超簡単!xmlファイルの変更だけでできるAndroidのタブレット対応の記事を参考にしつつ、dimens.xmlとvalues-sw600dp/dimens.xmlを使ってweightを定義すればいけるんじゃないかと思ってやってみました。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="@dimen/button1_weight"
android:text="button1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="@dimen/button1_weight"
android:text="button2" />
</LinearLayout>
values/dimens.xml
<resources>
<dimen name="button1_weight">2</dimen>
<dimen name="button2_weight">3</dimen>
</resources>
values-sw600dp/dimens.xml
<resources>
<dimen name="button1_weight">1</dimen>
<dimen name="button2_weight">9</dimen>
</resources>
しかし実行するとこんなエラーが出てきます。
Integer types not allowed (at 'button1_weight' with value '2').
IntegerがダメならFloat??と思ってやってみたものの変わらず。
どうやら、dimensに定義するのは数値+単位でないとダメなようです。
解決策
いい情報が見つかりました。
http://stackoverflow.com/questions/9461872/passing-layout-weight-reference-from-dimensions-dimens
dimensionsを使うのではなく、integers.xmlを新しく定義してそちらを使えと。
やってみます。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="@integer/button1_weight"
android:text="button1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="@integer/button2_weight"
android:text="button2" />
</LinearLayout>
values/integers.xml
<resources>
<integer name="button1_weight">2</integer>
<integer name="button2_weight">3</integer>
</resources>
values-sw600dp/integers.xml
<resources>
<integer name="button1_weight">1</integer>
<integer name="button2_weight">9</integer>
</resources>