// Obtain the screen size to properly set the button size and position
DisplayMetrics dm = new DisplayMetrics ();
GetWindowManager (). getDefaultDisplay (). getMetrics (dm );
Int width = dm. widthPixels;
Int height = dm. heightPixels;
// Customize the layout component
RelativeLayout layout = new RelativeLayout (this );
// Create 16 buttons here, with four buttons in each 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
Set the width and height of the button
If (I % 4 = 0 ){
J ++;
}
BtParams. leftMargin = 10 + (width-50)/4 + 10) * (I % 4); // locate the X coordinate
BtParams. topMargin = 20 + 55 * j; // ordinate position
Layout. addView (Btn [I], btParams); // Add the button to the layout component.
}
This. setContentView (layout );
// Configure listeners in batches
For (int k = 0; k <= Btn. length-1; k ++ ){
// No findId is required here, because the Id corresponding to the button has been determined during creation.
Btn [k]. setTag (k); // set a tag for the button to confirm which button is 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 relationship between internal classes, there are a lot of complicated internal classes.
Something to study
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 ();
}
});
}
Then, you can print the "press button:" I in Work_02 to confirm whether the listener is set correctly.
For example, press the button 0. In the corresponding page of Work_02, the "pressed button is 0" should be printed ".