- Home ›
- Android入門 ›
- FrameLayoutクラス ›
- HERE
位置を指定して子ビューを追加
広告
子ビューを追加する時に追加される位置を指定する方法を確認します。「FrameLayout」クラスの親クラスである「ViewGroup」クラスで用意されている「addView」メソッドを使います。
addView public void addView(View child, int index, LayoutParams params)
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.view.ViewGroup.LayoutParamsクラスのオブジェクト)を指定します。
そして2番目の引数で子ビューを追加する位置を指定します。「0」を指定すると先頭の位置へ、「1」を指定すると1番目と2番目の子ビューの間に追加されます。
具体的には次のように記述します。
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));
TextView text = new TextView(this);
text.setText("TextView");
text.setTextColor(Color.RED);
frameLayout.addView(text, 0, new ViewGroup.LayoutParams(WC, WC));
}
サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
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 Test03_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("Long Long Text");
text.setTextColor(Color.RED);
frameLayout.addView(text, 0, createParam(WC, WC));
}
private ViewGroup.LayoutParams createParam(int w, int h){
return new ViewGroup.LayoutParams(w, h);
}
}
ビルド後にエミュレーター上で実行します。
2番目に追加された子ビューは追加する位置として0番目を指定してありますので、先頭の位置に追加されています。
( Written by Tatsuo Ikura )
JavaDrive