I would like to know if its possible to add a view say textview directly from the activity (Dynamically) in android without actually having it in the layout ?
1 Answer
Inside your Activity:
TextView tv = new TextView(this);
tv.setId(42);
LayoutParams params = new LayoutParams(width, height);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
tv.setLayoutParams(params);
setContentView(tv);
Where myView is the View you want to add a View to. It can be of any type you want.
3 Comments
Saiesh
What if its a relative layout that i'm using ? Can i explicitly give the position where i want to add it using the id's like its done in the xml file ?
Saiesh
And in this case myview is a view that should already be given in the xml because unless and until u do that you wouldnt get an id for it right ? But i want to add a view without defining it in the xml .
Eric Nordvik
Try my latest edit to add a view programmatically without having it in xml.