2011-04-23 12 views
5

Escribí el siguiente código pero no entiendo cómo escribir el método OnclickListner() para todos los botones.¿Cómo crear varios botones en tiempo de ejecución? + android

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); 
    } 
} 

Respuesta

2

Puede utilizar un método interna anónima como esto:

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); 
+0

La cosa es que quiero escribir SQLite consulta para cada uno de los botones por separado. ¿Es mejor usar el caso swith? Hay 10 botones y cada uno tiene una consulta por separado. – Pramod

0

Si desea que los botones para hacer cosas diferentes, usted podría tener su actividad extienden OnClickListener, establezca b.setOnClickListener(this) en el bucle, y añadir algo así 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 comentarios ambiguos:

int iBtnID = v.getId(); 
switch (iBtnID) 
{ 
    case 101: 
    // do stuff; 
    break; 
    case 102: 
    // do other stuff 
    break; 
    // and so on 
} 
+0

insted of tag estoy usando setId(), por favor explique con la declaración del caso del interruptor. – Pramod

+0

@Pramod: Cambié el interruptor/caja a mi respuesta anterior. :) –

-1
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 
} 
} 
} 
+1

No veo cómo responde esto a la pregunta. El problema que tenía el OP era cómo manejar los eventos de clic para los botones. – Michael

Cuestiones relacionadas