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 .