2012年5月29日火曜日

View (ボタン等) を直線に並べて配置する (LinearLayout)

Android アプリで、View (ボタン等) を縦または横に直線に配置するには、リニアレイアウト (LinearLayout) クラスを使用します。



ここでは、リニアレイアウト (LinearLayout) を使ってテキスト (TextView)、編集テキスト (EditText)、ボタン (Button) を直線に並べて配置するサンプルを紹介します。


xml リソースファイルでリニアレイアウト (LinearLayout) を作成する場合は以下のように記述します。

■ リソース (xml ファイル)


layout/main.xml
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- ここに View を追加 -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtPass"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hintPass"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnPassSend"/>

</LinearLayout>

value/string.xml
<resources>
    <string name="txtPass">パスワード</string>
    <string name="hintPass">パスワードを入力して下さい</string>
    <string name="btnPassSend">パスワード送信</string>
</resources>


■ ソース (java ファイル)


LinearLayoutSample.java
import android.app.Activity;
import android.os.Bundle;

public class LinearLayoutActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // xml ファイルで定義したレイアウトリソースを設定
        setContentView(R.layout.main);
    }
}


■ LinearLayout クラスについての説明


LinearLayout タグの中に View を定義することで、その View を直線に並べて配置することができます。
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- ここに View を追加 -->

</LinearLayout>

”ここに View を追加” のところに Button 等を定義すれば、縦または横に並べて配置することができます。

縦に並べるか横に並べるかは orientation 属性で設定します。
vertical ・・・ 縦に並べてレイアウトします。
horizontal ・・・ 横に並べてレイアウトします。


0 件のコメント:

コメントを投稿