- Home ›
 - Android入門 ›
 - FrameLayoutクラス ›
 - HERE
 
位置を指定して子ビューを削除
広告
追加されている子ビューに対してインデックスを指定して子ビューを削除する方法を確認します。「FrameLayout」クラスの親クラスである「ViewGroup」クラスで用意されている「removeViewAt」メソッドを使います。
removeViewAt public void removeViewAt(int index)
Removes the view at the specified position in the group. Parameters: index the position in the group of the view to remove
1番目の引数には削除したい子のビューのインデックスを指定します。インデックスは0から開始されますので先頭のビューを削除するには0を指定します。
具体的には次のように記述します。
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, new ViewGroup.LayoutParams(WC, WC));
    frameLayout.removeViewAt(0);
}
					サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
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 Test05_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 button1 = new Button(this);
        button1.setText("Long Long Button");
        frameLayout.addView(button1, createParam(WC, WC));
        TextView text = new TextView(this);
        text.setText("Long Long TextView");
        text.setTextColor(Color.RED);
        frameLayout.addView(text, createParam(WC, WC));
        Button button2 = new Button(this);
        button2.setText("Short Button");
        frameLayout.addView(button2, createParam(WC, WC));
        frameLayout.removeViewAt(1);
    }
    private ViewGroup.LayoutParams createParam(int w, int h){
        return new ViewGroup.LayoutParams(w, h);
    }
}
					ビルド後にエミュレーター上で実行します。
					
					
3つの子ビューを追加していますが、インデックスが1番の子ビューは後で削除していますので2つの子ビューだけが表示されています。
( Written by Tatsuo Ikura )
				
JavaDrive