¿Cómo crear varios botones en tiempo de ejecución? Androide

Escribí el código siguiente pero no OnclickListner() cómo escribir el método de OnclickListner() para todos los botones.

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout layout = (LinearLayout) findViewById(R.id.ll1Relative); for (int i = 1; i < 10; i++) { LinearLayout.LayoutParams p = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ); Button b = new Button(this); b.setText(""+ i); b.setId(100+i); b.setWidth(30); b.setHeight(20); layout.addView(b, p); } } 

Puede utilizar un método interno anónimo como este:

 Button b = new Button(this); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on click } }); b.setText("" + i); b.setTag("button" + i); b.setWidth(30); b.setHeight(20); 

Si desea que los botones hagan cosas diferentes, puede hacer que su Actividad extienda OnClickListener, establezca b.setOnClickListener(this) en el bucle y añada algo como

 @Override public onClick(View v) { // get who called by String sTag = (String) v.getTag(); if (sTag.equals("button1")) { //do some stuff } else if (sTag.equals("button2")) { //do some other stuff } // and so on } 

Para manejar los clics.


Y estoy editando esto aquí porque la falta de saltos de línea hace que los comentarios sean ambiguos:

 int iBtnID = v.getId(); switch (iBtnID) { case 101: // do stuff; break; case 102: // do other stuff break; // and so on } 
 LinearLayout lin = (LinearLayout) findViewById(R.id.linearLayout); Button b1 = new Button(this); b1.setText("Btn"); b1.setId(int i=2); b1.setonClicklistenor(this); lin .addView(b1); 

y

 onclick (View v){ int i=v.getId(); if (i==2){ ///operation } } } 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.