Usually more accustomed to the use of XML files to add layouts and controls, the use of Java code in the activity to add controls is also a way, the following simple example: two.
1, Addcontentview
The Addcontentview function is similar to Setcontentview () to initialize the layout for activity:
1 Public classMainactivityextendsActivity {2 3 @Override4 protected voidonCreate (Bundle savedinstancestate) {5 Super. OnCreate (savedinstancestate);6 //Setcontentview (r.layout.activity_main);7TextView tv=NewTextView (Getapplicationcontext ());8Tv.settext ("Hello world1");9 Tv.setbackgroundcolor (color.gray);Ten tv.setgravity (gravity.center); One intx=layoutparams.match_parent; A inty=layoutparams.wrap_content; -Linearlayout.layoutparams params=Newlinearlayout.layoutparams (x, y); - This. Addcontentview (TV, params); the - - } -}
Adding controls in Java code can also set various properties, such as Settext,setbackgroundcolor in the example. Effect:
2, AddView
AddView adds a child control based on the parent control, similar to adding a control to the XML file:
Public class extends Activity { @Override protectedvoid onCreate (Bundle savedinstancestate) { Super . OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); = (linearlayout) Findviewbyid (r.id.ll); New TextView (Getapplicationcontext ()); Tv.settext ("Hello world2"); Tv.setbackgroundcolor (Color.gray); Tv.setgravity (gravity.center); Ll.addview (TV); }}
XML file:
1 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"2 Xmlns:tools= "Http://schemas.android.com/tools"3 Android:id= "@+id/ll"4 Android:layout_width= "Match_parent"5 Android:layout_height= "Wrap_content"6 android:orientation= "vertical" >7 8 </LinearLayout>
You can also add various properties of a control. Effect:
Adding Controls using Java code