子ビューを追加

広告

「LinearLayout」クラスのように「ViewGroup」クラスのサブクラスでは他のビューを子のビューとして含むことができます。ここでは子ビューを追加する方法を確認します。「LinearLayout」クラスの親クラスである「ViewGroup」クラスで用意されている「addView」メソッドを使います。

Adds a child view with the specified layout parameters.

Parameters:
  child  the child view to add
  params  the layout parameters to set on the child

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

LinearLayout.LayoutParamsクラス

「android.widget.LinearLayout.LayoutParams」クラスは「android.view.ViewGroup.LayoutParams」クラスのサブクラスです。コンストラクタの1つのは次のようになっています。

LayoutParams
public LinearLayout.LayoutParams(int w, int h)

1番目の引数に幅を、2番目の引数に高さを指定します。

指定方法はピクセル単位で指定するか「ViewGroup.LayoutParams.FILL_PARENT」又は「ViewGroup.LayoutParams.WRAP_CONTENT」を指定することができます。

「FILL_PARENT」を指定した場合にはビューを設定する画面の幅又は高さいっぱいに大きさを拡大します。また「WRAP_CONTENT」を指定した場合には表示のために必要となるサイズに自動的に幅又は高さを調整します。

※LayoutParamsクラスはいくつかのクラスで出てくるためどのクラスなのか分かるようにして注意して下さい。

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

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("Button");
    linearLayout.addView(button1, new LinearLayout.LayoutParams(WC, WC));

    Button button2 = new Button(this);
    button2.setText("Button");
    linearLayout.addView(button2, new LinearLayout.LayoutParams(100, 50));
}

サンプルプログラム

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

Test02_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 Test02_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 button = new Button(this);
        button.setText("Button");
        linearLayout.addView(button, createParam(WC, WC));

        TextView text = new TextView(this);
        text.setText("Text");
        linearLayout.addView(text, createParam(WC, WC));
    }

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

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

子ビューを追加

「LinearLayout」クラスはデフォルトでは水平方向に子ビューを配置していきます。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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