Android ViewGroup 是一种布局容器,用于管理子视图的位置和大小。我们可以通过以下几种方式来管理子视图:
添加子视图:可以通过 addView() 方法向 ViewGroup 中添加子视图。ViewGroup.addView(View child)移除子视图:可以通过 removeView() 或 removeViewAt() 方法从 ViewGroup 中移除子视图。ViewGroup.removeView(View view)ViewGroup.removeViewAt(int index)获取子视图:可以通过 getChildAt() 或 getChildCount() 方法获取 ViewGroup 中的子视图。ViewGroup.getChildAt(int index)ViewGroup.getChildCount()对子视图进行布局:可以通过 ViewGroup.LayoutParams 类来设置子视图的布局参数,如设置子视图的大小、位置等。ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);childView.setLayoutParams(params);自定义布局管理器:可以通过自定义 ViewGroup 来实现自定义的布局管理器,重写 onLayout() 方法来确定子视图的位置和大小。@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) { int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); // 设置子视图的位置和大小 child.layout(left, top, right, bottom); }}