手记

Spinner后下拉列表带图像

package com.example.spinner;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
private TextView textView;
private Spinner spinner;
private List<Map<String,Object>>dataList;
private SimpleAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView=(TextView)findViewById(R.id.textView);
    spinner= (Spinner) findViewById(R.id.spinner);
    dataList=new ArrayList<Map<String, Object>>();
    getData();
    adapter = new SimpleAdapter(this,dataList,R.layout.item,new String[]{"image", "text"}, new int[]{R.id.image, R.id.text});
    adapter.setDropDownViewResource(R.layout.item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            textView.setText("您选择的城市是:"+adapter.getItem(position));
        }

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

}
private void getData(){
    Map<String,Object> map1 = new HashMap<String,Object>();
    map1.put("image",R.mipmap.ic_launcher);
    map1.put("text","北京");
    Map<String,Object> map2 = new HashMap<String,Object>();
    map2.put("image",R.mipmap.ic_launcher);
    map2.put("text","上海");
    Map<String,Object> map3 = new HashMap<String,Object>();
    map3.put("image",R.mipmap.ic_launcher);
    map3.put("text","广州");
    Map<String,Object> map4 = new HashMap<String,Object>();
    map4.put("image",R.mipmap.ic_launcher);
    map4.put("text","深圳");
    Map<String,Object> map5 = new HashMap<String,Object>();
    map5.put("image",R.mipmap.ic_launcher);
    map5.put("text","西安");
    dataList.add(map1);
    dataList.add(map2);
    dataList.add(map3);
    dataList.add(map4);
    dataList.add(map5);
}

}

1人推荐
随时随地看视频
慕课网APP