如何创建两个下拉列表。其中一个依赖于第二个列表项。
答案 0 :(得分:0)
试试这个:
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Spinner
android:id="@+id/spinnerOne"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="@+id/spinnerTwo"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String country = "";
ArrayList<String> cityArrayListUSA;
ArrayList<String> cityArrayListSpain;
Spinner spinnerCountry;
Spinner spinnerCity;
ArrayAdapter<String> adapterCity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerCountry = (Spinner) findViewById(R.id.spinnerOne);
spinnerCountry.setOnItemSelectedListener(this);
spinnerCity = (Spinner) findViewById(R.id.spinnerTwo);
ArrayList<String> countryArrayList = new ArrayList<String>();
countryArrayList.add("USA");
countryArrayList.add("Spain");
cityArrayListUSA = new ArrayList<String>();
cityArrayListUSA.add("New York");
cityArrayListUSA.add("Orlando");
cityArrayListUSA.add("Seattle");
cityArrayListSpain = new ArrayList<String>();
cityArrayListSpain.add("Barcelona");
cityArrayListSpain.add("Madrid");
cityArrayListSpain.add("Cordova");
ArrayAdapter<String> adapterCountry = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,countryArrayList);
adapterCountry.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCountry.setAdapter(adapterCountry);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
country = parent.getItemAtPosition(position).toString();
if(country.equalsIgnoreCase("Spain")){
adapterCity = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,cityArrayListSpain);
}
else{
adapterCity = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,cityArrayListUSA);
}
adapterCity.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCity.setAdapter(adapterCity);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}