以编程方式在布局中添加视图并将 "clustered" 添加到中心

Add views programmatically in a layout and "clustered" to the center

我有一个相对布局,我想执行以下操作:
我想以编程方式在相对布局的右侧放置 X 文本视图。
X 可以是 1,也可以是 4。
我需要的是,最后我希望文本视图 "cluster" 朝向 center/vertically.
示例:

---------------------------  RelativeLayout  Top   


TextView


---------------------------  RelativeLayout Bottom    

有 2 个:

---------------------------  RelativeLayout  Top   

TextView-1  (the center is between Text-1 and Text-2)
TextView-2  

---------------------------  RelativeLayout Bottom    

有 3 个:

---------------------------  RelativeLayout  Top   

TextView-1
TextView-2
TextView-3

---------------------------  RelativeLayout Bottom    

等等
我尝试的是创建一个垂直方向的线性布局并将其添加到相对布局的左侧。
然后,如果适用于线性布局,我将文本视图添加为 children 但这不起作用:
1) 线性布局总是换行而不是匹配 parent 宽度
2) 我似乎无法将每个 child layout_gravity 设置为中心以测试会发生什么,因为如果我这样做:

((LinearLayout.LayoutParams)textView.getLayoutParams()).gravity = Gravity.CENTER;
这会影响文本而不是位置。
任何人都可以帮忙吗?即使是一个带有视图的简单示例也能帮助您理解这是如何完成的!

更新:这就是我现在做的:

LinearLayout linearLayout = new LinearLayout(theContext);  RelativeLayout.LayoutParams linearLayoutsParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.MATCH_PARENT);  linearLayoutsParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);  linearLayout.setOrientation(LinearLayout.VERTICAL);  linearLayout.setLayoutParams(linearLayoutsParams); 

据我了解,您不需要为 LinearLayout 个孩子设置重力。刚设置

android:layout_centerVertical="true"

LinearLayout 本身上(高度 = wrap_content,垂直方向)。类似于:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"

    android:gravity="center_vertical"
    android:orientation="vertical">

以编程方式(虽然未经测试):

LinearLayout linearLayout = new LinearLayout(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.CENTER_VERTICAL);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER_VERTICAL); //not sure it's needed
linearLayout.setLayoutParams(params);

线性布局规则不会传播到其子项:LL 将具有等间距的子项。但是我们将高度设置为 wrap_content 所以它会正好那么高,我们设置 center_vertical 所以它会保持居中。