子ビューを追加

広告

「FrameLayout」クラスのように「ViewGroup」クラスのサブクラスでは他のビューを子のビューとして含むことができます。ここでは子ビューを追加する方法を確認します。「FrameLayout」クラスの親クラスである「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.view.ViewGroup.LayoutParamsクラスのオブジェクト)を指定します。

ViewGroup.LayoutParamsクラス

ViewGroup.LayoutParamsクラスのコンストラクタの1つのは次のようになっています。

Creates a new set of layout parameters with the specified width and 
height.

Parameters:
  width  the width, either FILL_PARENT, WRAP_CONTENT or a fixed size 
    in pixels
  height  the height, either FILL_PARENT, WRAP_CONTENT or a fixed size 
    in pixels

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

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

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

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

private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 

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

    FrameLayout frameLayout = new FrameLayout(this);
    setContentView(frameLayout);

    Button button = new Button(this);
    button.setText("Button");
    frameLayout.addView(button, new ViewGroup.LayoutParams(WC, WC));
}

サンプルプログラム

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

Test02_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.Button;
import android.widget.TextView;
import android.view.ViewGroup;
import android.graphics.Color;

public class Test02_01 extends Activity
{
    private final int FP = ViewGroup.LayoutParams.FILL_PARENT; 
    private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 

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

        FrameLayout frameLayout = new FrameLayout(this);
        setContentView(frameLayout);

        Button button = new Button(this);
        button.setText("Button");
        frameLayout.addView(button, createParam(WC, WC));

        TextView text = new TextView(this);
        text.setText("TextView");
        text.setTextColor(Color.RED);
        frameLayout.addView(text, createParam(WC, WC));
    }

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

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

子ビューを追加

「FrameLayout」クラスは子ビューを左上の位置に追加された順で上書きされていきます。配置位置を指定することはできません。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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