删除布局

布局的layout文件内容:

----------------------------------------------------------------------------------

<?xmlversion="1.0"encoding="utf-8"?>

<LinearLayoutxmlns:android=""

android:orientation="vertical"android:layout_width="fill_parent"

android:layout_height="fill_parent"android:id="@+id/linearlayout">

<LinearLayoutandroid:id="@+id/LinearLayout01"

android:layout_width="wrap_content"android:layout_height="wrap_content">

<Buttonandroid:layout_height="wrap_content"android:id="@+id/add"

android:text="Add"android:layout_width="100px"></Button>

<Buttonandroid:layout_height="wrap_content"

android:layout_width="100px"android:text="Remove"android:id="@+id/remove"></Button>

</LinearLayout>

<TextViewandroid:id="@+id/TextView01"android:text="ThisistextView."

android:layout_width="fill_parent"android:gravity="center"

android:layout_height="50px"></TextView>

</LinearLayout>

----------------------------------------------------------------------------------

对应Activity的内容:

----------------------------------------------------------------------------------

packagecom.foxconn.dialog;

importandroid.app.Activity;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.view.View.OnClickListener;

importandroid.view.ViewGroup.LayoutParams;

importandroid.widget.Button;

importandroid.widget.LinearLayout;

publicclassDialogTestextendsActivityimplementsOnClickListener{

privateButtonadd_btn,remove_btn;

privateLinearLayoutlinearLayout;

privateintindex=0;

/**Calledwhentheactivityisfirstcreated.*/

@Override

publicvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

findViews();

register();

}

privatevoidregister(){

add_btn.setOnClickListener(this);

remove_btn.setOnClickListener(this);

}

privatevoidfindViews(){

add_btn=(Button)findViewById(R.id.add);

remove_btn=(Button)findViewById(R.id.remove);

linearLayout=(LinearLayout)findViewById(R.id.linearlayout);

}

protectedViewcreateView(){

Buttonbtn=newButton(this);

btn.setId(index++);

btn.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

btn.setText("aaaaaa"+index);

returnbtn;

}

privatevoidremoveView(){

//获取linearlayout子view的个数

intcount=linearLayout.getChildCount();

//研究整个LAYOUT布局,第0位的是含add和remove两个button的layout

//第count-1个是那个文字被置中的textview

//因此,在remove的时候,只能操作的是0<location<count-1这个范围的

//在执行每次remove时,我们从count-2的位置即textview上面的那个控件开始删除~

if(count-2>0){

//count-2>0用来判断当前linearlayout子view数多于2个,即还有我们点add增加的button

linearLayout.removeViewAt(count-2);

}

}

publicvoidonClick(Viewv){

switch(v.getId()){

caseR.id.add:

linearLayout.addView(createView(),1);

break;

caseR.id.remove:

removeView();

break;

default:

break;

}

}

}

相关推荐