Adding Controls using Java code

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.