How to add array of views to layout kotlin

Viewed 25

I want to add a list of views to a layout. The views are added, but are not showing up.

    val container:LinearLayout=findViewById(R.id.container)
    val card:FrameLayout=findViewById(R.id.card)
    card.setBackgroundColor(Color.parseColor("#E67E22"))

    val cardlimiter=4
    var cards= arrayOfNulls<FrameLayout>(10)
    for(i in 0 until cardlimiter)
    {
        cards[i]= FrameLayout(card.context).apply{
            setBackgroundColor(Color.parseColor("red"))
        }
        container.addView(cards[i])
    }
2 Answers

Nothing showing up because of FrameLayout you are trying to add doest not have any width, height or padding. You must specify a valid LayoutParam or nothing will shown with empty width or height.

Try to take a look at how to programmaticly create a valid layoutParam with width and height.

val params : ViewGroup.LayoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

FrameLayout(card.context).apply { 
    setBackgroundColor(Color.parseColor("red"))
    layoutParams = params
    setPadding(10, 10, 10, 10)
}
Related