Spinner together

3
  • I have a Spinner that is responsible for States in Brazil.
  • And another Spinner responsible for Capitals in Brazil.
  • I need to select State another Cities spinner to be unlocked and display their respective Capital that matches your State.

Is this possible?

    
asked by anonymous 11.01.2017 / 14:49

2 answers

4

There are several ways to do this, however I'll show you a way using the setOnItemSelectedListener() method. This way, I check if the selected item is the first one using position == 0 . In the first position there is the phrase Escolha o Estado . If this position is selected, spinner for Cities will remain disabled using setEnabled(false) . See below:

MainActivity.java

libs :

import android.widget.AdapterView;
import android.widget.Spinner;

code :

    final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
    final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);

    spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0)
                spinner2.setEnabled(false);
            else
                spinner2.setEnabled(true);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

activity_main.xml

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/estados"
    android:prompt="@string/estados_prompt" />

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/cidades"
    android:prompt="@string/cidades_prompt" />

string.xml

<string name="estados_prompt">Escolha o estado</string>
<string-array name="estados">
    <item>Escolha o Estado</item>
    <item>São Paulo</item>
    <item>Rio De Janeiro</item>
    <item>Minas Gerais</item>
</string-array>

<string name="cidades_prompt">Escolha a cidade</string>
<string-array name="cidades">
    <item>Escolha a cidade</item>
    <item>Atibaia</item>
    <item>Petrópolis</item>
    <item>Belo Horizonte</item>
</string-array>

Note: This is a very simple example, because in practice the ideal would be to filter the city according to the state.

For more details on Spinner 's, read the documentation .

    
11.01.2017 / 15:26
2

To enable / disable a view, use the setEnabled () method.

Spinner capitais = (Spinner) findViewById(R.id.spinnerCapitais);
capitais.setEnabled(true) // para ativar a view
capitais.setEnabled(false) // para desativar a view
    
11.01.2017 / 15:20