- Home ›
 - Android入門 ›
 - LinearLayoutクラス ›
 - HERE
 
追加される方向を指定
広告
「addView」メソッドなどを使って子ビューを追加していくとデフォルトでは水平方向に順に追加されていきます。ここでは追加する方向として水平方向又は垂直方向を指定する方法を確認します。「LinearLayout」クラスで用意されている「setOrientation」メソッドを使います。
setOrientation public void setOrientation(int orientation)
Should the layout be a column or a row. Related XML Attributes: android:orientation Parameters: orientation Pass HORIZONTAL or VERTICAL. Default value is HORIZONTAL.
引数には追加される方向を表す値をを指定します。次のどちらかの定数を指定して下さい。
LinearLayout.HORIZONTAL 水平方向(左から右へ) LinearLayout.VERTICAL 垂直方向(上から下へ)
設定を行わなかった場合は追加される方向は水平方向となります。
具体的には次のように記述します。
private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 
@Override public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    setContentView(linearLayout);
    Button button1 = new Button(this);
    button1.setText("Button1");
    linearLayout.addView(button2, new LinearLayout.LayoutParams(WC, WC));
    Button button2 = new Button(this);
    button2.setText("Button2");
    linearLayout.addView(button2, new LinearLayout.LayoutParams(WC, WC));
}
					サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
package jp.javadrive.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.TextView;
import android.view.ViewGroup;
public class Test04_01 extends Activity
{
    private final int FP = ViewGroup.LayoutParams.FILL_PARENT; 
    private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 
    /** Called with the activity is first created. */
    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(linearLayout);
        Button button1 = new Button(this);
        button1.setText("Button1");
        linearLayout.addView(button1, createParam(WC, WC));
        TextView text = new TextView(this);
        text.setText("Text");
        linearLayout.addView(text, createParam(WC, WC));
        Button button2 = new Button(this);
        button2.setText("Button2");
        linearLayout.addView(button2, createParam(WC, WC));
    }
    private LinearLayout.LayoutParams createParam(int w, int h){
        return new LinearLayout.LayoutParams(w, h);
    }
}
					ビルド後にエミュレーター上で実行します。
					
					
今回は縦方向を指定しましたので上から下へ向かって順にビューが追加されています。
( Written by Tatsuo Ikura )
				
JavaDrive