- Home ›
- Android入門 ›
- FrameLayoutクラス ›
- HERE
子ビューを削除
広告
FrameLayout内に追加されている子ビューを削除する方法を確認します。まずは削除したいビューを指定して削除を行います。「FrameLayout」クラスの親クラスである「ViewGroup」クラスで用意されている「removeView」メソッドを使います。
removeView public void removeView(View view)
Parameters: view 削除するビュー
1番目の引数には削除したい子のビューのオブジェクトを指定します。指定するオブジェクトは既に追加されたオブジェクトでなければなりません。
具体的には次のように記述します。
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.removeView(button);
}
サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
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 Test04_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));
frameLayout.removeView(button);
}
private ViewGroup.LayoutParams createParam(int w, int h){
return new ViewGroup.LayoutParams(w, h);
}
}
ビルド後にエミュレーター上で実行します。
2つの子ビューを追加していますが、最初に追加したビューは後で削除していますので2番目に追加された子ビューだけが表示されています。
( Written by Tatsuo Ikura )
JavaDrive