In androidui layout, XML is usually used to layout controls. This is convenient and intuitive, but sometimes it needs to be dynamically generated, here are two simple examples to illustrate how to dynamically add controls:
1. dynamically add two vertical buttons
@ Override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> // setcontentview (R. layout. main); <br/> final linearlayout layout2 = new linearlayout (this); <br/> layout2.setorientation (linearlayout. vertical); <br/> button btn1 = new button (this); <br/> setcontentview (layout2); <br/> button btn2 = new button (this ); <br/> btn1.settext ("button1"); <br/> btn2.settext ("button2"); <br/> layout2.addview (btn1); <br/> layout2.addview (btn2 ); </P> <p> setcontentview (layout2); <br/>}
Final linearlayout layout2 = new linearlayou (this );
Define a linearlayout. The parameter is "context" here, that is, "this ".
Layout2.setorientation (linearlayout. Vertical );
Set the layout format to vertical in vertical arrangement
2. dynamically Add a button in the button click event
Onclicklistener listen1; <br/> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> // setcontentview (R. layout. main); <br/> final linearlayout layout2 = new linearlayout (this); <br/> layout2.setorientation (linearlayout. vertical); <br/> button btn1 = new button (this); <br/> setcontentview (layout2); <br/> button btn2 = new button (this ); <br/> btn1.settext ("button1"); <br/> btn2.settext ("button2"); <br/> layout2.addview (btn1); <br/> layout2.addview (btn2 ); <br/> listen1 = new onclicklistener () {<br/> Public void onclick (view v) {<br/> settitle ("Click button1 "); <br/> button btn3 = new button (v. getcontext (); <br/> layout2.addview (btn3); <br/> btn3.settext ("button3"); </P> <p >}< br/> }; <br/> btn1.setonclicklistener (listen1); <br/>}
The difference from the previous example is that the control is dynamically added to the onclicklistener of the button. Note that the button btn3 = new button (v. getcontext); parameter v. getcontext is the context of the current view. Why is this used as the context in Example 1, therefore, this can be directly used as an activity.
Check that the classes derived from context are:
Java. Lang. Object |
Bytes |
Android. content. Context |
Known direct subclassesContextwrapper , Mockcontext
Contextwrapper |
Proxying Implementation of context that simply delegates all of its callto Another context. |
Mockcontext |
A mock Context Class. |
|
Known indirect subclasses
Abstractinputmethodservice
,
Activity
,
Activitygroup
,
Aliasactivity
,
Application
,
Contextthemewrapper
,
Expandablelistactivity
,
Inputmethodservice
,
Intentservice
,
Isolatedcontext
,
Launcheractivity
,
Listactivity
,
Mockapplication
,
Mutablecontextwrapper
,
Preferenceactivity
,
Renamingdelegatingcontext
,
Service
,
Tabactivity