简体   繁体   English

如何从onResume上的片段中删除所有小部件

[英]How to remove all widgets from a fragment on onResume

I have a fragment that contains many buttons that were added to the layout dynamically. 我有一个片段,其中包含许多动态添加到布局中的按钮。 Because they were added dynamically I didn't assign them ID's to reference them. 因为它们是动态添加的,所以我没有为其分配ID来引用它们。

In my main activity's onResume, I want to be able to just clear all widgets in this certain fragment without needing to reference each button by ID to remove it. 在我的主要活动的onResume中,我希望能够仅清除此特定片段中的所有小部件,而无需通过ID引用每个按钮将其删除。 Is there a way I can do this? 有办法吗?

Possibly running the following command but applied to all Buttons without referencing particular ID's: 可能运行以下命令,但适用于所有按钮,而没有引用特定的ID:

button.setVisibility(View.GONE);

EDIT: 编辑:

for (int i = 0; i < R.layout.grid_cell.getCount(); i++) {
View v = R.layout.grid_cell.getChildAt(i);
R.layout.grid_cell.removeView(v);
// or you can check the view
//if (v instanceof Button) {
//    layout.removeView(v);
//}
}

in your onResume() 在你的onResume()中

for (int i = 0; i < layout.getChildCount(); i++) {
        View v = layout.getChildAt(i);
        layout.removeView(v);
      // or you can check the view
      //if (v instanceof Button) {
      //    layout.removeView(v);
      //}
    }

Edit "layout" is not layout file. 编辑 “布局”不是布局文件。

RelativeLayout layout= (RelativeLayout) findViewById(R.id.root);

If you're using RecyclerView you must return View of each row item. 如果您使用的是RecyclerView,则必须返回每个行项目的View。 For example if you want remove views in onResume(), you can return the view like your own itemClickListener into activity. 例如,如果要在onResume()中删除视图,则可以将视图像自己的itemClickListener一样返回到活动中。 As the result the View is your row's root View. 结果,该视图是您行的根视图。 And than you can get view.getChildCount() and put it into loop. 然后,您可以获取view.getChildCount()并将其放入循环中。 It doesn't matter GridLayout or others. GridLayout或其他无关紧要。 The think is same. 想法是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM