位置を指定して子ビューを追加

広告

子ビューを追加する時に追加される位置を指定する方法を確認します。「LinearLayout」クラスの親クラスである「ViewGroup」クラスで用意されている「addView」メソッドを使います。

Adds a child view with the specified layout parameters.

Parameters:
  child  the child view to add
  index  the position at which to add the child
  params  the layout parameters to set on the child

1番目の引数には追加したい子のビュー、3番目の引数には子ビューの表示レイアウトを表すLayoutParamsクラスのオブジェクト(android.widget.LinearLayout.LayoutParamsクラスのオブジェクト)を指定します。

そして2番目の引数で子ビューを追加する位置を指定します。「0」を指定すると先頭の位置へ、「1」を指定すると1番目と2番目の子ビューの間に追加されます。

具体的には次のように記述します。

private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 

@Override public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    LinearLayout linearLayout = new LinearLayout(this);
    setContentView(linearLayout);

    Button button1 = new Button(this);
    button1.setText("Button1");
    linearLayout.addView(button1, new LinearLayout.LayoutParams(WC, WC));

    Button button2 = new Button(this);
    button2.setText("Button2");
    linearLayout.addView(button2, new LinearLayout.LayoutParams(WC, WC));

    Button button3 = new Button(this);
    button3.setText("Button3");
    linearLayout.addView(button3, 1, new LinearLayout.LayoutParams(WC, WC));
}

この場合、「Button1」「Button3」「Button2」の順でビューは表示されます。

サンプルプログラム

それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。

Test03_01.java

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 Test03_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);
        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, 1, createParam(WC, WC));
    }

    private LinearLayout.LayoutParams createParam(int w, int h){
        return new LinearLayout.LayoutParams(w, h);
    }
}

ビルド後にエミュレーター上で実行します。

位置を指定して子ビューを追加

追加された順番とは別に「Button2」は位置として「1」番目を指定して追加していますので1番目と2番目のビューの間に追加されています。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。