Creating LinearLayout Programmatically/Dynamically with Multiple Views

You want that hierarchy programmatically.

- LinearLayout(horizontal)
- ImageView
- LinearLayout(vertical)
- TextView
- TextView
- TextView
- TextView

Ok lets start with Parent LinearLayout

LinearLayout parent = new LinearLayout(context);

parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
parent.setOrientation(LinearLayout.HORIZONTAL);

//children of parent linearlayout

ImageView iv = new ImageView(context);

LinearLayout layout2 = new LinearLayout(context);

layout2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
layout2.setOrientation(LinearLayout.VERTICAL);

parent.addView(iv);
parent.addView(layout2);

//children of layout2 LinearLayout

TextView tv1 = new TextView(context);
TextView tv2 = new TextView(context);
TextView tv3 = new TextView(context);
TextView tv4 = new TextView(context);

layout2.addView(tv1);
layout2.addView(tv2);
layout2.addView(tv3);
layout2.addView(tv4);

And you are done 🙂

Leave a Comment