Java 在布局中以编程方式添加视图,并;“集群式”;中锋
我有一个相对布局,我想做以下工作:Java 在布局中以编程方式添加视图,并;“集群式”;中锋,java,android,android-layout,android-relativelayout,Java,Android,Android Layout,Android Relativelayout,我有一个相对布局,我想做以下工作: 我想以编程方式将X文本视图放置在相对布局的右侧。 X可以是1,也可以是4。 我需要的是,最终我希望文本视图“群集”到中心/垂直方向。 示例: --------------------------- RelativeLayout Top TextView --------------------------- RelativeLayout Bottom 第2条: --------------------------- Relati
我想以编程方式将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\u 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
childs。刚定
android:layout_centerVertical="true"
在LinearLayout
自身上(高度=包裹内容,垂直方向)。比如:
<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">
线性布局规则不会传播到其子对象:LL将具有等间距的子对象。但是我们将高度设置为包裹内容
,这样它就正好那么高了,我们将居中(垂直)
设置为居中。如何?这就是我现在所做的:LinearLayout LinearLayout=newlinearlayout(上下文);RelativeLayout.LayoutParams LinearLayoutParams=新的RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_内容,RelativeLayout.LayoutParams.MATCH_父项);LinearLayoutParams.addRule(RelativeLayout.ALIGN\u PARENT\u LEFT);linearLayout.setOrientation(linearLayout.VERTICAL);linearLayout.setLayoutParams(LinearLayoutParams)
或多或少看起来您只需要添加另一条规则:linearLayoutParams.addRule(RelativeLayout.CENTER\u VERTICAL)
。我还将在高度属性上使用WRAP\u内容更改MATCH\u PARENT。但是,我目前的规则使线性布局本身与PARENT的左侧对齐。如果我添加新规则,它是否适用于儿童?编辑了我的答案。为了更好地了解发生了什么,您可以在手机的开发者设置中激活“布局界限”(不确定英文措辞)。
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);