简体   繁体   English

无法以编程方式在其父布局中对齐中心自定义线性布局

[英]Cannot align center custom linear layout inside its parent layout programmatically

I have a custom linear layout which is a red path as show in the image I attached in the link below that consist a textview and a button. 我有一个自定义的线性布局,这是一条红色路径,如我在下面的链接中所附加的图像中所示,该文本包含一个textview和一个按钮。 I would like to make the text and button center inside the gray path by making the red path match parent, but I can not achieve that. 我想通过使红色路径与父项匹配来使文本和按钮在灰色路径内居中,但我无法实现这一点。 I used to try many ways by setting layout param to match parent and set gravity center programmatically to make those element center. 我过去通过设置布局参数以匹配父级并以编程方式设置重心以使这些元素居中来尝试多种方法。 But those ways are not worked. 但是这些方法不起作用。 enter image description here 在此处输入图片说明

This my code example: 这是我的代码示例:

val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
layoutParams.gravity = Gravity.CENTER
grayLayout.addView(redLayout)
grayLayout.layoutParams = layoutParams

Any clue to help me out. 任何帮助我的线索。 Thanks in advance. 提前致谢。

Do not reuse the same layout params for 2 different objects. 不要对2个不同的对象重复使用相同的布局参数。 Create a new layout params for each object. 为每个对象创建一个新的布局参数。

layoutParams.gravity = Gravity.CENTER 

sets the gravity of the contained views in the layout. 设置布局中包含视图的重力。
So if you want to center the gray layout inside the red layout 因此,如果您想将灰色布局放在红色布局的中心
apply this attribute to the red layout. 将此属性应用于红色布局。
You can also do it in xml: 您也可以在xml中执行此操作:

android:gravity="center"

I already found the answer, I forgot to set the layoutParams to my redLayout by programmatically, I only set it in xml file. 我已经找到了答案,我忘了以编程方式将layoutParams设置为redLayout,我只在xml文件中进行了设置。 Since the red layout is the custom layout, setting match_parent inside xml is not work unless we set it by programmatically. 由于红色布局是自定义布局,因此除非我们通过编程方式设置,否则在XML中设置match_parent无效。 Thanks everyone for taking your time to contribute this question. 感谢大家抽出宝贵时间来提出这个问题。

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

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