2012-03-24 16 views
8

Estoy inflando un botón que tiene xml, varias veces y puedo hacerlo perfectamente pero el problema es que cuando hago clic en el botón, quiero mostrar en qué botón se hace clic.Al inflar un diseño xml dinámicamente varias veces, ¿cómo puedo diferenciar o identificar los widgets de botón?

public class InflateExActivity extends Activity implements OnClickListener { 
    /** Called when the activity is first created. */ 

    Button b; 


    LinearLayout lLayout; 
    LayoutInflater inflater; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 


     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     for (int i = 0; i < 3; i++) { 

      inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      b = (Button) inflater.inflate(R.layout.buttons, null); 
      t = (TextView) inflater.inflate(R.layout.texts, null); 


      b.setTag(i); // you'll get 0,1,2 as 

      lLayout = (LinearLayout) findViewById(R.id.layout1); 
      lLayout.addView(b); 

      b.setOnClickListener(this); 

     } 

    } 

    public void onClick(View v) { 

     } 

} 
+0

Usted sabe que los nombres de variables pueden, y deben ser, de más de una letra de longitud. – stimms

Respuesta

4

elementos que está agregando mediante programación, debe tener que asignarles identificadores.

b.setId(1); 

Editado:

public class DynamicLayoutActivity extends Activity implements OnClickListener{ 
private static final int MY_BUTTON = 9000; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    LinearLayout ll = (LinearLayout)findViewById(R.id.layout1); 

    // add button 
    Button b = new Button(this); 
    b.setText("Button added dynamically!"); 
    b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    b.setId(MY_BUTTON); 
    b.setOnClickListener(this); 
    ll.addView(b); 
} 
public void onClick(View v) { 
     Toast toast; 
     Log.w("ANDROID DYNAMIC VIEWS:", "View Id: " + v.getId()); 
     switch (v.getId()) { 
     case MY_BUTTON: 
      toast = Toast.makeText(this, "Clicked on my dynamically added button!", Toast.LENGTH_LONG); 
      toast.setGravity(Gravity.TOP, 25, 400); 
      toast.show();  
     } 
    } 

ACTUAL:

public class InflateExActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     LinearLayout lLayout; 
     Button b = null; 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     for(int i=0;i<3;i++){ 
      final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      b = (Button) inflater.inflate(R.layout.buttons, null); 
      b.setId(i); 
      lLayout = (LinearLayout) findViewById(R.id.layout1); 
      lLayout.addView(b); 
      b.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       Toast.makeText(InflateExActivity.this, "Button Clicked :"+v.getId(), 
         Toast.LENGTH_LONG).show(); 
      } 
     }); 
    } 
} 
+0

¿Puedes decirnos cómo usarlo en el código? – Rookie

+0

referir esto http://as400samplecode.blogspot.in/2011/10/android-programmatically-generate.html –

+0

ver mi respuesta editada –

3

utilizar la etiqueta vista

View.setTag (etiqueta Object);

Puede establecer una cadena o un objeto complejo como una clase para la etiqueta.

+0

¿Puedes decirnos cómo usarlo en el código? – Rookie

6

Puede usar setTag() para cada botón. Dentro del bucle for puede asignar button.setTag(). Y puede usar getTag() para recuperar la etiqueta del botón. Después de inflar el diseño, agregue una etiqueta a su botón

EDIT2: Debe inflar el diseño y luego buscar su id de botón. Consulte a continuación:

public class InflateExActivity extends Activity { 
      /** Called when the activity is first created. */ 
      @Override 
      public void onCreate(Bundle savedInstanceState) { 
       LinearLayout lLayout; 
       final Button b = null; 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.main); 
       for(int i=0;i<3;i++){ 
        final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View v = inflater.inflate(R.layout.buttons, null); 
b = v.findViewById(R.id.your_button_id); 
    //     b = (Button) inflater.inflate(R.layout.buttons, null); 
         b.setTag(i); // you'll get 0,1,2 as tags 
        lLayout = (LinearLayout) findViewById(R.id.layout1); 
        lLayout.addView(b); 
        b.setOnClickListener(new OnClickListener() { 

         public void onClick(View v) { 
    int specificButton = (Integer)v.getTag();//Changed here....... 
          Toast.makeText(InflateExActivity.this, "Button Clicked"+Integer.toString(specificButton), 
            Toast.LENGTH_LONG).show(); 
         } 
        }); 
       } 
      } 
     } 
+0

¿Puedes editar en código y publicar ... no puedo hacerlo? – Rookie

+0

siempre muestra el botón 2 presionado .. – Rookie

+0

todavía está mostrando el botón 2 clic .. último botón. – Rookie

Cuestiones relacionadas