Spinner实现下拉框

Spinner实现下拉框_第1张图片
image.png

Spinner实现下拉框_第2张图片
image.png

页面设置



java代码

在这个功能实现部分采用俩种效果
第一种是简单的地方选择,只有文字的显示下拉框,采用的适配器是ArrayAdapter
第二种是有图片文字的下拉框选择,采用的适配器是SimpleAdapter ,相对比较难一点
以下就是实现俩种效果的java功能代码

 private TextView textView;
    private Spinner spinner;
    private List list;
    private  ArrayAdapter arrayAdapter;
    private SimpleAdapter simpleAdapter;
    private List>dataList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner);
        textView=(TextView) findViewById(R.id.textView);
        textView.setHint("您選擇的是:");
        spinner=(Spinner) findViewById(R.id.spinner);
        //設置數據源
//        list= new ArrayList();
//        list.add("北京");
//        list.add("上號");
//        list.add("內蒙古");
//        list.add("深圳");
//         arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_spinner_item,list);
//        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        spinner.setAdapter(arrayAdapter);
//        spinner.setOnItemSelectedListener(this);
        dataList=new ArrayList>();
        simpleAdapter=new SimpleAdapter(this,this.getData(),R.layout.item,new String[]{"image","text"},new int[]{R.id.image,R.id.text});
        simpleAdapter.setDropDownViewResource(R.layout.item);
        spinner.setAdapter(simpleAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView parent, View view, int position, long id) {
             textView.setText("您选择的是"+simpleAdapter.getItem(position));
            }

            @Override
            public void onNothingSelected(AdapterView parent) {
               textView.setText("NONE");
            }
        });

    }
//    @Override
//    public void onItemSelected(AdapterView parent, View view, int position, long id) {
//         String cityName = simpleAdapter.getItem(position);
//        textView.setText("您選擇的是:"+cityName);
//    }
//
//    @Override
//    public void onNothingSelected(AdapterView parent) {
//
//    }
    private  List> getData(){
       Map map=new HashMap();
        map.put("image",R.drawable.ic_cardid);
        map.put("text","北京");
        dataList.add(map);
        Map map1=new HashMap();
        map1.put("image",R.drawable.ic_cardid);
        map1.put("text","內蒙古");
        dataList.add(map1);
        Map map2=new HashMap();
        map2.put("image",R.drawable.ic_cardid);
        map2.put("text","天津");
        dataList.add(map2);
        Map map3=new HashMap();
        map3.put("image",R.drawable.ic_cardid);
        map3.put("text","上海");
        dataList.add(map3);
        return dataList;
    }

实现的最终效果是这样的:


Spinner实现下拉框_第3张图片
image.png

第二种效果图


Spinner实现下拉框_第4张图片
image.png

你可能感兴趣的:(Spinner实现下拉框)