Android spinner下拉框连动

本代码主要功能  

1、 向拉菜单 spinner添加数据

2、下拉菜单连动

以下是核心代码


//定义变量
private Spinner spinner3;
private Spinner spinner4;
private Map<String,List<String>> gaderMap=new HashMap<String, List<String>>();
private List<String> gader=new ArrayList<>();
private List<String> student1=new ArrayList<>();
private List<String> student2=new ArrayList<>();
private List<String> selectStudents=new ArrayList<>();

//绑定变量
spinner3=findViewById(R.id.Spinner03);
spinner4=findViewById(R.id.Spinner04);

//填充变量
gader.add("1班");
gader.add("2班");

student1.add("罗分明");
student1.add("lqwvje");
student2.add("www.luofenming.com");
student2.add("www.995w.com");
gaderMap.put(gader.get(0),student1);
gaderMap.put(gader.get(1),student2);



//事件
spinner3.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, gader));//spinner3添加数据
final ArrayAdapter<String> selectAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, selectStudents);
spinner4.setAdapter(selectAdapter);
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {//选中项监听
    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
    Toast.makeText(SpinnerTest.this, spinner3.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
    selectStudents.clear();//清空集合内容
    selectStudents.addAll(gaderMap.get(spinner3.getSelectedItem().toString()));//添加集合内容
    selectAdapter.notifyDataSetChanged();//通知道适配器
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
});


评论