ConstraintLayout inside LinearLayout not working
K

1

7

I have to programmatically add a view (whose root view can be anything) into LinearLayout but if that view is a ConstraintLayout, it won't work as expected. Why is this happening, because according to my understanding, a child view must work regardless of what its parent view is. How do I make this work?

Problem is very simple and but I am not able to find any question addressing this problem.

I am attaching screenshots to show the distorted view:

ORIGINAL VIEW _____________________ VIEW AFTER ADDING INSIDE LINEAR LAYOUT

enter image description here _______ enter image description here

And here is the code:

override fun setContentView(view: View?) {
    val toolbar = layoutInflater.inflate(R.layout.view_toolbar, null, false)
    titleView = toolbar.findViewById(R.id.title) as TextView

    val finalView = LinearLayout(this)
    finalView.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
    finalView.orientation = LinearLayout.VERTICAL
    finalView.addView(toolbar)
    finalView.addView(view)
    super.setContentView(finalView)
}

I am overriding the Activity's setContentView function.

Klansman answered 27/11, 2017 at 17:9 Comment(3)
did you try explicitely set the LayoutParams when doing finalView.addView(view) ? You might also give it a weight of 1 so that it occupies all the remaining space. EDIT: actually, I'm pretty sure LinearLayoutParams.weight=1 is what you wantSylvanus
Weight? Should I really try it? Because weight has nothing to do with the fact that why ConstraintLayout is acting funny inside LinearLayout.Klansman
@Sylvanus man you beauty! It worked. Not the weight thing but explicitely setting LayoutParams when addingViewKlansman
K
5

As it turns out, there was nothing wrong with ConstraintLayout inside LinearLayout. I just had to explicitly add LayoutParams while adding my view.

override fun setContentView(view: View?) {
    val toolbar = layoutInflater.inflate(R.layout.view_toolbar, null, false)
    titleView = toolbar.findViewById(R.id.title) as TextView

    val finalView = LinearLayout(this)
    finalView.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
    finalView.orientation = LinearLayout.VERTICAL
    finalView.addView(toolbar)
    finalView.addView(view, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT))
    super.setContentView(finalView)
}
Klansman answered 27/11, 2017 at 17:23 Comment(1)
for me I was missing orientationSosa

© 2022 - 2024 — McMap. All rights reserved.