删除linearlayout中的所有项目

时间:2012-03-20 10:50:17

标签: android android-linearlayout

我创建了一个替换为xml项的linearlayout。在这个线性布局中,我动态地放置了一些textview,因此不需要从xml中取出它们。现在我需要从linearlayout中删除这些textview。我试过这个:

if(((LinearLayout) linearLayout.getParent()).getChildCount() > 0)
    ((LinearLayout) linearLayout.getParent()).removeAllViews();

但它不起作用。 我能怎么做? 谢谢,马蒂亚

2 个答案:

答案 0 :(得分:142)

为什么你写了linearLayout.getParent()你应该直接在LinearLayout上做这一切

if(((LinearLayout) linearLayout).getChildCount() > 0) 
    ((LinearLayout) linearLayout).removeAllViews(); 

答案 1 :(得分:5)

您好请尝试使用此代码为我工作

public class ShowText extends Activity {
    /** Called when the activity is first created. */
    LinearLayout linearLayout;
    TextView textView,textView1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView=new TextView(this);
        textView1=new TextView(this);
        textView.setText("First TextView");
        textView1.setText("First TextView");

        linearLayout=(LinearLayout) findViewById(R.id.mn);
        linearLayout.addView(textView);
        linearLayout.addView(textView1);
        linearLayout.removeAllViews();

    }
}