我有一个相对的布局,我想做以下工作:
我想以编程的方式在相对布局的右边放置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); 发布于 2015-07-28 18:49:44
据我所知,你不需要给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);线性布局规则不会传播到它的childs: LL将具有等距的childs。但是我们设定了wrap_content的高度,所以它会是那么高,我们设置了center_vertical,所以它将保持中心位置。
https://stackoverflow.com/questions/31684614
复制相似问题