ホームへ戻る

3.2 LinearLayout


 まずは最も基本的なLinearLayoutです。
これまでに何度か使用してきたレイアウトなので既に理解されている方もいらっしゃるかもしれませんね。

ここではブラウザで良くあるようなレイアウトを考えてみましょう。



このような、「戻るボタン」「URL表示欄」「ブックマークボタン」が上部にあり、
下部はWebViewで覆われているというレイアウトです。

WebViewとは、ブラウザ機能を持ったViewです。(ここではその機能を利用しません)

さて、ここで困るのが、ボタンやテキスト表示部は横方向に並んでいるのですが、
それに対してWebViewは縦方向に並んでいますから、一つのレイアウトでは表現できそうにありません。

そこでレイアウトを入れ子にしてみましょう。

これまでに出てきたように、レイアウトは既に、デフォルトでLinearLayout(縦方向)で囲まれています。
よって、横方向のレイアウトを追加します。



「レイアウト」の「LinearLayout(Horizontal)」を右側にドロップして下さい。

その枠の中に「Button」「プレーンテキスト」「Button」の順番でドロップして下さい。



順番に置いて・・



このようにして下さい。
後は、画面下部にWebViewを置いて下さい。



すると、既に位置関係は完璧になりました。

ではボタンの文字列を変更してみましょう。
文字列を変更する方法として今までとは別の方法をご紹介します。

まず左のボタンを右クリックし



「Edit Text」を選択します。
出てきたダイアログの「New String」をクリックします。



ストリングに「←」
New R.string. に「back」
と入力します。
これによって、"←"という文字列は今後 R.string.back で利用可能になります。



今作った「back」を選択してOKをクリックします。
これで、ボタンの表示文字列が「←」になりました。

もちろん、これまでの通り、プロパティから変更も出来ます。
右のボタンはプロパティの「Text」から「★」に変更してみましょう。



これで完成です。



ソースを確認してみましょう。



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/back" />

        <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" >
            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="★" />
        
    </LinearLayout>

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


縦方向(vertical)レイアウトの中に、横方向(Horizontal)なレイアウトが存在します(orientationを省略するとhorizontalになります)。
horizontalなLinearLayoutの中にButtonとEditTextが存在しているので、これは横に並び、
その外にあるWebViewは縦方向に並んでいるというわけです。

EditTextが幅いっぱいに表示されているのは、EditTextにだけウェイトの指定があるためです。

→分からないことがあれば掲示板で質問して下さい


Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.

- Remical Soft -