Android Development Dynamic Create multiple buttons

Source: Internet
Author: User

Get the screen size to set the button size and position appropriately

Displaymetrics dm = new Displaymetrics ();

Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM);

int width = dm.widthpixels;

int height = dm.heightpixels;

Custom Layout Components

Relativelayout layout = new Relativelayout (this);

Create 16 buttons here, 4 buttons per line

Button btn[] = new BUTTON[16];

Int j =-1;

for (int i=0; i<=15; i++) {

Btn[i]=new Button (this);

Btn[i].setid (2000+i);

Btn[i].settext ("button" +i);

Relativelayout.layoutparams btparams = new Relativelayout.layoutparams ((width-50)/4,40); Set

Width and height of the reset button

if (i%4 = = 0) {

j + +;

}

Btparams.leftmargin = + + ((width-50)/4+10) * (i%4); Horizontal alignment

Btparams.topmargin = + 55*j; Ordinate positioning

Layout.addview (Btn[i],btparams); Put the button into the layout component

}

This.setcontentview (layout);

Batch setup Monitoring

for (int k = 0; k <= btn.length-1; k++) {

There is no need for findid, since the creation of the time has determined which button corresponds to which ID

Btn[k].settag (k); Set a marker for the button to confirm which button was pressed

Btn[k].setonclicklistener (New Button.onclicklistener () {

@Override

public void OnClick (View v) {

int i = (Integer) v.gettag (); Here I cannot be defined externally because of the inner class relationships, the inner classes are a lot of tedious

Something to study well.

Intent Intent = new Intent ();

Intent.setclass (Work_01.this, Work_02.class);

Bundle bundle = new bundle ();

Bundle.putint ("Count", I);

Intent.putextras (bundle);

StartActivity (Intent);

Work_01.this.finish ();

}

});

}

You can then print the "pressed button as:" In work_02 to confirm that the settings are listening correctly.

For example, press button 0, in the work_02 corresponding page, you should print the "button pressed: 0".

Android Development Dynamic Create multiple buttons

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.