title: Creating Multiple ImageButtons in a Single Activity Programatically
body: <p>I have a single image <code>myimage.png</code> which is placed in my <code>res</code>-<code>drawable</code> folder.
  I have to create 50 ImageButtons in an activity all using this same image.</p>
  
  <p>And then when a user clicks i need to pop out a toast saying button number i was clicked.</p>
  
  <p>Here's what I have done:</p>
  
  <pre><code>public class AllImageButtons extends Activity {
  
  int screendimesionx;
  int screendimesiony;
  ImageButton imageButton;
  ImageButton allImageButtons[] = new ImageButton[50];
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.allbuttonimages);
  
      DisplayMetrics metrics = new DisplayMetrics();
      getWindowManager().getDefaultDisplay().getMetrics(metrics);
      screendimesiony = metrics.heightPixels;
      screendimesionx = metrics.widthPixels;
  
      createButtonsAndAddListener();
  
  }
  
  
  
  public void createButtonsAndAddListener() {
      for (int i = 0; i &lt; 50; i++) {
          imageButton = (ImageButton) findViewById(R.id.myimage);
          float buttonimagey = imageButton.getDrawable().getBounds().height();
          float buttonimagex = imageButton.getDrawable().getBounds().width();
          float xspaceforeachbuttonimage = screendimesionx/50;
          LayoutParams par = (LayoutParams)imageButton.getLayoutParams();
          par.leftMargin = (int) (i*xspaceforeachbuttonimage);
          par.topMargin = 0;
          imageButton.setLayoutParams(par);
          allImageButtons[i] = imageButton;
          allImageButtons[i].setOnClickListener(new OnClickListener() {
  
              @Override
              public void onClick(View arg0) {
  
                  Toast.makeText(AllbuttonimagesForSelectionActivity.this,
                          "ImageButton is clicked!", Toast.LENGTH_SHORT)
                          .show();
  
              }
  
  
          });
  
      }
  }}
  </code></pre>
  
  <p>and then there is the associated xml file  <code>allbuttonimages.xml</code>:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical" &gt;
  
      &lt;ImageButton
          android:id="@+id/imageButton1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:src="@drawable/myimage" /&gt;
  
  &lt;/LinearLayout&gt;
  </code></pre>
  
  <p>This xml layout displays only the last ImageButton from the loop.</p>
  
  <p><strong>My Question:</strong></p>
  
  <p>How can i dynamically create all 50 ImageButtons from the same image in a single view ?</p>