【发布时间】:2018-03-14 20:01:37
【问题描述】:
如何从小部件中删除所有子视图?例如,我有一个 GridView,我动态地将许多其他 LinearLayouts 膨胀到其中;稍后在我的应用程序中,我希望从该 GridView 重新开始并清除其所有子视图。我该怎么做? TIA。
【问题讨论】:
标签: android
如何从小部件中删除所有子视图?例如,我有一个 GridView,我动态地将许多其他 LinearLayouts 膨胀到其中;稍后在我的应用程序中,我希望从该 GridView 重新开始并清除其所有子视图。我该怎么做? TIA。
【问题讨论】:
标签: android
viewGroup.removeAllViews()
适用于任何视图组。在您的情况下,它是 GridView。
http://developer.android.com/reference/android/view/ViewGroup.html#removeAllViews()
【讨论】:
ViewGroup?
您可以使用此功能仅删除 ViewGroup 中的某些类型的视图:
private void clearImageView(ViewGroup v) {
boolean doBreak = false;
while (!doBreak) {
int childCount = v.getChildCount();
int i;
for(i=0; i<childCount; i++) {
View currentChild = v.getChildAt(i);
// Change ImageView with your desired type view
if (currentChild instanceof ImageView) {
v.removeView(currentChild);
break;
}
}
if (i == childCount) {
doBreak = true;
}
}
}
【讨论】:
试试这个
RelativeLayout relativeLayout = findViewById(R.id.realtive_layout_root);
relativeLayout.removeAllViews();
这段代码对我有用。
【讨论】:
试试这个
void removeAllChildViews(ViewGroup viewGroup) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof ViewGroup) {
if (child instanceof AdapterView) {
viewGroup.removeView(child);
return;
}
removeAllChildViews(((ViewGroup) child));
} else {
viewGroup.removeView(child);
}
}
}
【讨论】: