删除linearlayout中的所有项目


69

我创建一个引用xml项目的linearlayout。在这个linearlayout内部,我动态地放置了一些textview,因此无需从xml中获取它们。现在,我需要从linearlayout中删除这些textview。我尝试了这个:

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

但这不起作用。我能怎么做?谢谢,Mattia

Answers:


174

为什么写linearLayout.getParent(),应该直接在LinearLayout上完成所有这些操作

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

16
无需添加计数检查,因为removeAllViews()内部已经执行了此操作。来自 removeAllViews()源代码if (count <= 0) { return; }
令人震惊的

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();

    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.