Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Adding LinearLayouts in Android

I'm trying to add LinearLayouts dynamically but it's just not working. I think I just need another set of eyes to look it over. Can anyone help me?

LinearLayout parentLayout = (LinearLayout)findViewById(R.id.parentLayout);
        lLayout = new LinearLayout[8];
        for(int i = 0; i < lLayout.length; i++) {
            lLayout[i] = new LinearLayout(this);
            lLayout[i].setId(i);
            lLayout[i].setOrientation(LinearLayout.HORIZONTAL);
            if(i%2 == 0) {
                lLayout[i].setBackgroundColor(Color.GREEN);
            } else {
                lLayout[i].setBackgroundColor(Color.MAGENTA);
            }
            parentLayout.addView(lLayout[i]);
        }
like image 536
Nelson.b.austin Avatar asked Dec 08 '25 09:12

Nelson.b.austin


1 Answers

You need to set LayoutParams, try adding this:

lLayout[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
like image 127
ElefantPhace Avatar answered Dec 09 '25 23:12

ElefantPhace