Android 如何以编程方式将父视图添加到子视图?

Android 如何以编程方式将父视图添加到子视图?,android,Android,我想将水平滚动视图作为父视图添加到子视图线性布局。是否有一种方法可以在Android中以编程方式将父视图添加到子视图?您可以从原始父视图中删除子视图,将其添加到新父视图,然后将新父视图添加到原始父视图 比如: // Get reference to the child view val childView = R.findViewById<LinearLayout>(R.id.myChildLinearLayout) // Create horizontal scroll view

我想将
水平滚动视图
作为父视图添加到子视图
线性布局
。是否有一种方法可以在Android中以编程方式将父视图添加到子视图?

您可以从原始父视图中删除子视图,将其添加到新父视图,然后将新父视图添加到原始父视图

比如:

// Get reference to the child view
val childView = R.findViewById<LinearLayout>(R.id.myChildLinearLayout)

// Create horizontal scroll view (or inflate)
val horizScrollView = HorizontalScrollView(context)

// Remove child view from original parent
removeView(child)

//TODO: setup new layout params on childView as needed

// Add child view to the horizontal scroll view
horizScrollView.addView(childView)

//TODO: setup layout params on horizontal scrollview as needed

// Add horizontal scrollview to the original parent
addView(horizScollView)
//获取对子视图的引用
val childView=R.findViewById(R.id.myChildLinearLayout)
//创建水平滚动视图(或充气)
val horizScrollView=水平滚动视图(上下文)
//从原始父视图中删除子视图
移除视图(子级)
//TODO:根据需要在childView上设置新布局参数
//将子视图添加到水平滚动视图
horizScrollView.addView(childView)
//TODO:根据需要在水平滚动视图上设置布局参数
//将水平滚动视图添加到原始父视图
添加视图(水平视图)