简体   繁体   中英

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

在此输入图像描述 _______ 在此输入图像描述

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.

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

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