删除linearlayout中的所有项目

pin*_*dol 59 android android-linearlayout

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

if(((LinearLayout) linearLayout.getParent()).getChildCount() > 0)
    ((LinearLayout) linearLayout.getParent()).removeAllViews();
Run Code Online (Sandbox Code Playgroud)

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

MKJ*_*ekh 151

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

if(((LinearLayout) linearLayout).getChildCount() > 0) 
    ((LinearLayout) linearLayout).removeAllViews(); 
Run Code Online (Sandbox Code Playgroud)

  • 无需添加计数检查,因为`removeAllViews()`已在内部进行此操作。来自`removeAllViews()`源代码`if(count <= 0){return; }` (5认同)

Man*_*nju 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();

    }
}
Run Code Online (Sandbox Code Playgroud)