Adding content to a linear layout dynamically?
In your onCreate()
, write the following
LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);
view1
, view2
and view3
are your TextView
s. They're easily created programmatically.
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);
You can achieve LinearLayout cascading like this:
LinearLayout root = (LinearLayout) findViewById(R.id.my_root);
LinearLayout llay1 = new LinearLayout(this);
root.addView(llay1);
LinearLayout llay2 = new LinearLayout(this);
llay1.addView(llay2);
I found more accurate way to adding views like linear layouts in kotlin (Pass parent layout in inflate() and false)
val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)