SoFunction
Updated on 2025-03-11

Android (Android) dynamically create multiple buttons and add listening events

1. Get the screen size to reasonably set the button size and position

 DisplayMetrics dm = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(dm);
 int width = ;
 int height = ;

2. Customize layout component

 RelativeLayout layout = new RelativeLayout(this); 

3. Create 16 buttons here, 4 buttons are placed 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); 
   btParams = new  ((width-50)/4,40);

4. Set the width and height of the button

 if (i%4 == 0) {
   j++;
  }
   = 10+ ((width-50)/4+10)*(i%4); //Horizontal positioning   = 20 + 55*j; //Dimensional positioning  (Btn[i],btParams); //Put the button into the layout component }
  (layout);

5. Set up listening in batches

for (int k = 0; k <= -1; k++) {
 //The findId is not needed here, because when creating it, it has been determined which button corresponds to which Id Btn[k].setTag(k);    //Set a mark for the button to confirm which button has been pressed
 Btn[k].setOnClickListener(new () {
 @Override
  public void onClick(View v) {
   int i = (Integer) ();

   Intent intent = new Intent();
   (Work_01.this, Work_02.class);
   Bundle bundle = new Bundle();
   ("count", i);
   (bundle);
   startActivity(intent);
   Work_01.();     
  }
  });
 }

Then, you can print out the "pressed button:" i in Work_02 to confirm whether the set listening is correct.

For example, press button 0, on the page corresponding to Work_02, "The button pressed is: 0".