Android中Spinner二级联动动态加载数据

原创作品,允许转载,转载时请说明出处。

最近在做一个项目中用到了两个Spinner,我觉得这样写起来更简单。

xml文件:

        

        

item:

        

代码:

public class XxjkFragment extends Fragment {

private View view;
private Spinner xxjk_fl_sp;
private Spinner xxjk_rw_sp;
private ArrayList> arrayList = new ArrayList<>();
private List list = new ArrayList<>();
private List list1 = new ArrayList<>();
private List list2 = new ArrayList<>();
private List list3 = new ArrayList<>();


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.fragment_xxjk,null);

    initView();

    initData();

    listen();

    return view;
}

private void listen() {

    xxjk_fl_sp.setAdapter(new ArrayAdapter(getActivity(),R.layout.item,list));

    xxjk_fl_sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView parent, View view, int position, long id) {
            xxjk_rw_sp.setAdapter(new ArrayAdapter(getActivity(),R.layout.item,arrayList.get(position)));
        }

        @Override
        public void onNothingSelected(AdapterView parent) {

        }
    });


}

private void initView() {
    xxjk_fl_sp = ((Spinner) view.findViewById(R.id.xxjk_fl_sp));
    xxjk_rw_sp = ((Spinner) view.findViewById(R.id.xxjk_rw_sp));
}

private void initData() {
    list.add("北京");
    list.add("河北");
    list.add("数字");

    list1.add("海淀");
    list1.add("朝阳");
    list1.add("昌平");

    list2.add("张家口");
    list2.add("保定");
    list2.add("石家庄");

    list3.add("123");
    list3.add("456");
    list3.add("789");

    arrayList.add((ArrayList) list1);
    arrayList.add((ArrayList) list2);
    arrayList.add((ArrayList) list3);

}

}

我写在了fragment里边,在activity中也一样。

你可能感兴趣的:(Android中Spinner二级联动动态加载数据)