繁体   English   中英

在布局中以编程方式添加视图并“聚集”到中心

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

我有一个相对布局,我想执行以下操作:
我想以编程方式将 X 文本视图放在相对布局的右侧。
X 可以仅为 1 或最多为 4。
我需要的是,最后我希望文本视图“聚集”到中心/垂直方向。
例子:

---------------------------  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    

等等。
我尝试的是创建一个垂直方向的线性布局并将其添加到相对布局的左侧。
然后,如果适用于线性布局,我将文本视图添加为子视图,但这不起作用:
1) 线性布局总是换行而不是匹配父宽度
2)我似乎无法将每个子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 将有等距的孩子。 但是我们将 height 设置为wrap_content所以它会那么高,我们设置center_vertical这样它会保持居中。

暂无
暂无

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

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