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