かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

AndroidのLinearLayoutを組み合わせてSwingのBorderLayoutみたいな配置をする方法

Androidアプリのレイアウトの基本はLinearLayoutにあり!と勝手に信じているのですが、こいつちょっと癖があったのでメモしておきます。
基本的に、縦か横にアイテムを並べてくれるシンプルなレイアウトなのですが、weightを指定することで配置時の幅の重みづけをすることができます。

ここで陥りがちなのは、weightとheightやwidthのfill_parentを組み合わせるというパターンです。これをやると、どうも思ったように重みづけがされません。wrap_contentをwidthやheightに設定してると思ってくれたようなレイアウトにしてくれます。
ということで、SwingのBorderLayoutと同じようなレイアウトを実現するには以下のような方法でいけます。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/layout_root"
	android:layout_width="fill_parent" android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical">
	<Button 
        android:text="Top Button" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_weight="0" />
	<LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_weight="1">
        <Button 
            android:text="L" 
            android:layout_width="wrap_content"
            android:layout_height="fill_parent" 
            android:layout_weight="0" />
        <Button 
            android:text="Center Button" 
            android:layout_width="wrap_content"
            android:layout_height="fill_parent" 
            android:layout_weight="1" />
        <Button 
            android:text="R" 
            android:layout_width="wrap_content"
            android:layout_height="fill_parent" 
            android:layout_weight="0" />
    </LinearLayout>
    <Button 
        android:text="Bottom Button" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_weight="0" />
</LinearLayout>

この画面を表示させると以下のようになります。

ポイントは、さっきも言ったようにweightを指定するものには配置に重みづけをしたい方向の幅をwrap_contentにすること。weightのデフォルト値は0ですが、今回のサンプルは明示的に0でも指定しています。(特に意味はないです)

これとTableLayoutを組み合わせれば割と思い通りのレイアウトが出来そうです。