There are several ways to do this, however I’ll show you a way using the method setOnItemSelectedListener()
. 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, the spinner
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" />
xml string.
<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.
In the -> Parent and view parameters: Cannot resolve Symbol Parent... In setOnItemSelectedListener tells the same thing too. And in Adapterview<? > informs -> 'Expression expected'
– Júnior
@Junior didn’t understand your doubt.
– viana
Parent, View, Adapterview<? >. They are giving error. I am putting this code inside my "activityMenu.java"
– Júnior
Its orientation is the same as what I put inside "strings.xml" and "activity_menu.xml".
– Júnior
@Junior you imported the libraries correctly?
– viana
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.Appcompatactivity; import android.view.View; import android.widget.Adapterview; import android.widget.Spinner;
– Júnior
@Junior here is working perfectly. Try to clear your project.
– viana
@Junior understood why it’s wrong. You have to insert this excerpt inside your onCreate.
– viana
Sorry for the shame...' Thank you!
– Júnior