删除线性布局中的所有项目

我创建了一个引用 xml 项的线性布局。在这个线性布局中,我动态地放置了一些文本视图,因此不需要从 xml 中获取它们。现在我需要从线性布局中删除这些文本视图。我试过了:

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

但是没用。 我该怎么办? 谢谢 Mattia

63739 次浏览

Why you wrote linearLayout.getParent()?

You should call this directly on LinearLayout:

linearLayout.removeAllViews();

Hi Please try this code its working for me

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


}
}