Spinner的简单级联主要用到了二维数组~
代码呈上:
public class MainActivity extends AppCompatActivity { PRivate Spinner spProvince; private Spinner spCity; private String[] province= {"河南省","浙江省"};//二维数组用于根据省的选择来相应的显示城市 private String[][] citys= {{"鹤壁市","郑州市","商丘市","沈丘市"},{"杭州市","宁波市","衢州市","温州市"}}; private ArrayAdapter<String> provinceAdapter; private ArrayAdapter<String> cityAdapter;@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spProvince = (Spinner) findViewById(R.id.spProvince); spCity = (Spinner) findViewById(R.id.spCity);//省的适配器绑定 provinceAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,province); spProvince.setAdapter(provinceAdapter);//市的适配器绑定 cityAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1); spCity.setAdapter(cityAdapter);//监听省的Spinner选项的选择 spProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {//根据省的选择i来改变市的数据 String[] city = citys[i];//适配器清零 cityAdapter.clear();//添加市的数据 cityAdapter.addAll(city); spCity.setSelection(0); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); }再来看一下布局文件:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.shen.fourth.MainActivity"> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/spProvince" /> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/spCity"/></LinearLayout>就是一个垂直的线性布局,放置两个Spinner,一个用于显示省,一个用于显示城市。ok,就这样可以实现Spinner的简单的级联~
新闻热点
疑难解答