Pregunta

Estoy haciendo una aplicación de Android, donde hay una vista compuesta por cientos de botones, cada uno con una devolución de llamada específica. Ahora, me gustaría configurar estas devoluciones de llamada usando un bucle, en lugar de tener que escribir cientos de líneas de código (para cada uno de los botones).

Mi pregunta es: ¿Cómo puedo usar FindViewByid sin tener que escribir estáticamente cada ID de botón? Esto es lo que me gustaría hacer:

    for(int i=0; i<some_value; i++) {
       for(int j=0; j<some_other_value; j++) {
        String buttonID = "btn" + i + "-" + j;
        buttons[i][j] = ((Button) findViewById(R.id.buttonID));
        buttons[i][j].setOnClickListener(this);
       }
    }

¡Gracias por adelantado!

¿Fue útil?

Solución

Deberías usar getIdentifier()

for(int i=0; i<some_value; i++) {
   for(int j=0; j<some_other_value; j++) {
    String buttonID = "btn" + i + "-" + j;
    int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
    buttons[i][j] = ((Button) findViewById(resID));
    buttons[i][j].setOnClickListener(this);
   }
}

Otros consejos

Puede intentar hacer un int [] que contenga todos sus ID de botón y luego iterar sobre eso:

int[] buttonIDs = new int[] {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }

for(int i=0; i<buttonIDs.length; i++) {
    Button b = (Button) findViewById(buttonIDs[i]);
    b.setOnClickListener(this);
}

Puede usar la etiqueta si desea acceder.

en onClick

int i=Integer.parseInt(v.getTag);

Pero no puedes acceder a ese botón como este.

Simplemente cree el botón programáticamente

por Button b=new Button(this);

Crear botón personalizado en el código Java en lugar de XML como mostré a continuación

Button bs_text[]= new Button[some_value];

    for(int z=0;z<some_value;z++)
        {
            try
            {

            bs_text[z]   =  (Button) new Button(this);

            }
            catch(ArrayIndexOutOfBoundsException e)
            {
                Log.d("ArrayIndexOutOfBoundsException",e.toString());
            }
        }

Si su vista de nivel superior solo tiene esas vistas de botones como niños, puede hacer

for (int i = 0 ; i < yourView.getChildCount(); i++) {
    Button b = (Button) yourView.getChildAt(i);
    b.setOnClickListener(xxxx);
}

Si hay más vistas presentes, necesitaría verificar si el seleccionado es uno de sus botones.

Si por alguna razón no puedes usar el getIdentifier() función y/o conoce los posibles ID de antemano, puede usar un interruptor.

int id = 0;

switch(name) {
    case "x":
        id = R.id.x;
        break;
    etc.etc.
}

String value = findViewById(id);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top