简体   繁体   中英

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

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. Since the red layout is the custom layout, setting match_parent inside xml is not work unless we set it by programmatically. Thanks everyone for taking your time to contribute this question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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