Android adds controls dynamically in the layout container

Source: Internet
Author: User

Here, with a small demo, you can control the dynamic addition of controls in the layout container to add the button control dynamically as an example, adding other controls to the same principle.

1, AddView

Adding controls to the layout container

2, Removeview

Delete existing controls in the layout container

3, use, to a small demo will understand

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);//Generate a linearlayout as a layout container to dynamically add 3 buttonfinal linearlayout layout = new LinearLayout (this); Layout.setorientation (linearlayout.vertical); Setcontentview (layout);//Generate 3 buttonfinal button btn1 = New button (this ), Btn1.settext ("1"), Btn1.settext ("Button1"), final button btn2 = New button (this), Btn2.settext ("2"), Btn2.settext (" Button2 "), final button btn3 = New button (this), Btn3.settext (" 3 "); Btn3.settext (" Button3 ");// Dynamically add three buttons to Layout.addview (BTN1); Layout.addview (BTN2); Layout.addview (BTN3);//Click on the button to first delete the layout Add the local container layout so that the added control will be sorted to the end to understand the idea of dynamically adding controls Btn1.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {Layout.removeview (BTN1); Layout.addview (BTN1);}}); /Same as BTN1 Btn2.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {Layout.removeview ( BTN2); Layout.addview (BTN2);}); /same reason as Btn1 BTN3.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {Layout.removeview (BTN3); Layout.addview (BTN3);}}); Setcontentview (layout);}}

4.

Android adds controls dynamically in the layout container

Related Article

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.