package com.sorgs.administrator.spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
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 Activity{
private TextView textView;
private Spinner spinner;
private SimpleAdapter adapter;
private List<Map<String, Object>> dataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
spinner = (Spinner) findViewById(R.id.spinner);
textView.setText("您选择的是城市是北京");
dataList = new ArrayList<Map<String, Object>>();
getData();
//2.新建ArrayAdapter(数组适配器)
adapter=new SimpleAdapter(this, dataList, R.layout.item, new String[]{"image","text"}, new int[]{R.id.image,R.id.text});
//3.adapter设置一个下拉列表样式
adapter.setDropDownViewResource(R.layout.item);
//4.spinner加载适配器
spinner.setAdapter(adapter);
//5.spinner设置监听器
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
textView.setText("您选择的是:" + adapter.getItem(arg2));
}
public void onNothingSelected(AdapterView<?> arg0) {
textView.setText("NONE");
}
});
}
private void getData() {
Map<String,Object>map = new HashMap<String,Object>();
map.put("image", R.mipmap.ic_launcher);
map.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", "深圳");
dataList.add(map);
dataList.add(map2);
dataList.add(map3);
dataList.add(map4);
}
}