Search code examples
androidandroid-layoutandroid-activityandroid-linearlayoutandroid-constraintlayout

ConstraintLayout inside LinearLayout not working


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.


Solution

  • 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)
    }