问题描述
在android开发中,如何实现两个spinner 关联,即点击第一个spinner后可以在第二个spinner中动态添加数据?
解决方案
main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><Spinner android:id="@+id/list1"android:layout_width="90px" android:layout_height="42px"android:layout_marginTop="3px"android:layout_marginLeft="60px"/><Spinner android:id="@+id/list2"android:layout_width="90px" android:layout_height="42px"android:layout_marginTop="3px"android:layout_marginLeft="60px"/></LinearLayout>Activitypublic class AndroidTestActivity extends Activity {private Spinner spinner1;private Context context;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);context = this;spinner1 = (Spinner) findViewById(R.id.list1); String[] m={"aaa","bbb"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m); spinner1.setAdapter(adapter); spinner1.setOnItemSelectedListener(spinnerSelectedListener);}private Spinner.OnItemSelectedListener spinnerSelectedListener = new Spinner.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { String selectedValue = (String)spinner1.getSelectedItem(); Spinner spinner2 = (Spinner) findViewById(R.id.list2); String[] m={selectedValue};ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, m); spinner2.setAdapter(adapter); } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } };}