Establecer el elemento seleccionado de spinner programáticamente


Estoy trabajando en un proyecto de Android y estoy usando un spinner que utiliza un adaptador de matriz que se rellena desde la base de datos.

No puedo averiguar cómo puedo configurar el elemento seleccionado programáticamente de la lista. Por ejemplo, si, en el spinner tengo los siguientes elementos:

  • Categoría 1
  • Categoría 2
  • Categoría 3

¿Cómo haría programáticamente Categoría 2 el elemento seleccionado cuando se crea la pantalla. Estaba pensando que podría ser similar a c # I. E Spinner.SelectedText = "Categoría 2" pero no parece haber ningún método similar a este para Android.

Author: Sathya, 2012-06-17

17 answers

Utilice lo siguiente: spinnerObject.setSelection(INDEX_OF_CATEGORY2).

 604
Author: Arun George,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-17 15:41:29

Ninguna de estas respuestas me dio la solución, solo trabajó con esto:

mySpinner.post(new Runnable() {
    @Override
    public void run() {
        mySpinner.setSelection(position);
    }
});
 63
Author: Marco HC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-26 04:30:39
public static void selectSpinnerItemByValue(Spinner spnr, long value) {
    SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
    for (int position = 0; position < adapter.getCount(); position++) {
        if(adapter.getItemId(position) == value) {
            spnr.setSelection(position);
            return;
        }
    }
}

Puedes usar lo anterior como:

selectSpinnerItemByValue(spinnerObject, desiredValue);

& por supuesto, también puede seleccionar por índice directamente como

spinnerObject.setSelection(index);
 29
Author: Yaqub Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-24 22:13:03

Alguna explicación (al menos para Fragmentos - nunca probado con Actividad pura). Espero que ayude a alguien a entender mejor Android.

La respuesta más popular de Arun George es correcta, pero no funciona en algunos casos.
La respuesta de Marco HC utiliza Runnable que es un último recurso debido a la carga adicional de la CPU.

La respuesta es simplemente elegir el lugar correcto para llamar a setSelection(), por ejemplo funciona para me:

@Override
public void onResume() {
    super.onResume();

    yourSpinner.setSelection(pos);
 }

Pero no funcionará en onCreateView () . Sospecho que esa es la razón del interés por este tema.

El secreto es que con Android no puedes hacer nada que quieras en ningún método - oops:( - los componentes pueden simplemente no estar listos. Como otro ejemplo - no puedes desplazar ScrollView ni en onCreateView () ni en onResume () (ver la respuesta aquí)

 24
Author: sberezin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:59

¿Por qué no usas tus valores de la base de datos y los guardas en una ArrayList y luego usas:

yourSpinner.setSelection(yourArrayList.indexOf("Category 1"));
 10
Author: RicardoSousaDev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-08 14:30:19

Para encontrar un valor y seleccionarlo:

private void selectValue(Spinner spinner, Object value) {
    for (int i = 0; i < spinner.getCount(); i++) {
        if (spinner.getItemAtPosition(i).equals(value)) {
            spinner.setSelection(i);
            break;
        }
    }
}
 9
Author: Ferran Maylinch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-24 22:13:13

Puede hacer un método genérico para este tipo de trabajo como lo hago en mi UtilityClass que es

public void SetSpinnerSelection(Spinner spinner,String[] array,String text) {
    for(int i=0;i<array.length;i++) {
        if(array[i].equals(text)) {
            spinner.setSelection(i);
        }
    }
}
 6
Author: ZygoteInit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-24 22:13:27

Tengo un SimpleCursorAdapter, así que tengo que duplicar los datos para usar el respose en este post. Por lo tanto, te recomiendo que intentes de esta manera:

for (int i = 0; i < spinnerRegion.getAdapter().getCount(); i++) {
    if (spinnerRegion.getItemIdAtPosition(i) == Integer
        .valueOf(signal.getInt(signal
            .getColumnIndexOrThrow("id_region")))) {
        spinnerRegion.setSelection(i);
        break;
    }
}

Creo que es una manera real

 3
Author: pazfernando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-25 19:18:05

Esto es trabajo para mí.

 spinner.setSelection(spinner_adapter.getPosition(selected_value)+1);
 2
Author: Arpit Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-21 10:01:07

Puede configurar fácilmente así: spinner.setSelection(1), en lugar de 1, puede establecer cualquier posición de la lista que le gustaría mostrar.

 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-10 19:41:35

La solución óptima es:

    public String[] items= new String[]{"item1","item2","item3"};
    // here you can use array or list 
    ArrayAdapter adapter= new ArrayAdapter(Your_Context, R.layout.support_simple_spinner_dropdown_item, items);
    final Spinner itemsSpinner= (Spinner) findViewById(R.id.itemSpinner);
itemsSpinner.setAdapter(adapter);

Para obtener la posición del elemento, agregue automáticamente la siguiente instrucción

itemsSpinner.setSelection(itemsSpinner.getPosition("item2"));
 2
Author: Naham Al-Zuhairi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-29 18:57:24

Si tienes una lista de contactos, puedes ir por esto:

((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));
 1
Author: Maddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-30 15:10:26

Sé que ya está contestada, pero código simple para seleccionar un elemento, muy simple:

spGenre.setSelection( ( (ArrayAdapter) spGenre.getAdapter()).getPosition(client.getGenre()) );
 1
Author: Dante,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-22 22:00:51
  for (int x = 0; x < spRaca.getAdapter().getCount(); x++) {
            if (spRaca.getItemIdAtPosition(x) == reprodutor.getId()) {
                spRaca.setSelection(x);
                break;
            }
        }
 1
Author: Julio Cezar Riffel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-28 17:01:07

En mi caso, este código me salvó el día:

public static void selectSpinnerItemByValue(Spinner spnr, long value) {
    SpinnerAdapter adapter = spnr.getAdapter();
    for (int position = 0; position < adapter.getCount(); position++) {
        if(adapter.getItemId(position) == value) {
            spnr.setSelection(position);
            return;
        }
    }
}
 1
Author: Juan Pablo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-22 16:23:05

Esto se indica en comentarios en otras partes de esta página, pero pensé que era útil para sacarlo en una respuesta:

Al usar un adaptador, he encontrado que el spinnerObject.setSelection(INDEX_OF_CATEGORY2) necesita ocurrir después la llamada setAdapter; de lo contrario, el primer elemento es siempre la selección inicial.

// spinner setup...
spinnerObject.setAdapter(myAdapter);
spinnerObject.setSelection(INDEX_OF_CATEGORY2);

Esto se confirma revisando el código AbsSpinner para setAdapter.

 0
Author: Andy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-18 15:56:34

Esto funcionó para mí:

@Override
protected void onStart() {
    super.onStart();
    mySpinner.setSelection(position);
}

Es similar a la solución de @sberezin pero llamando a setSelection() en onStart().

 -1
Author: JosinMC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-31 17:08:28