package?com.example.administrator.spinner; import?android.content.Context; import?android.support.v7.app.ActionBarActivity; import?android.os.Bundle; import?android.view.Menu; import?android.view.MenuItem; 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?android.widget.Toast; import?java.lang.reflect.Array; import?java.util.ArrayList; import?java.util.HashMap; import?java.util.List; import?java.util.Map; import?java.util.HashMap; public?class?MainActivity?extends?ActionBarActivity?implements?Spinner.OnItemSelectedListener{ ????private?TextView?textView; ????private?Spinner?spinner; ????private?List?data; ????private?List<Map>?data_list; ????private?Context?mContext; ????@Override ????protected?void?onCreate(Bundle?savedInstanceState)?{ ????????super.onCreate(savedInstanceState); ????????setContentView(R.layout.activity_main); ????????mContext?=?this; ????????textView?=?(TextView)findViewById(R.id.text); ????????spinner?=?(Spinner)findViewById(R.id.spinner); ????????//1?數(shù)據(jù)源 ????????data?=?new?ArrayList(); ????????data.add("北京"); ????????data.add("上海"); ????????data.add("廣州"); ????????data.add("重慶"); ????????data_list?=?new?ArrayList<Map>(); ????????//2?適配器 ????????ArrayAdapter?adapter?=?new?ArrayAdapter(this,android.R.layout.simple_list_item_1,data); ????????SimpleAdapter?s_adapter?=?new?SimpleAdapter(this,getData(),R.layout.item,new?String[]{"text","pic"},new?int[]{R.id.text,R.id.pic}); ????????//3?適配器樣式 ????????//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); ????????adapter.setDropDownViewResource(R.layout.item); ????????//4?注入適配器 ???????//?spinner.setAdapter(adapter); ????????spinner.setAdapter(s_adapter); ????????spinner.setOnItemSelectedListener(this); ????} ????@Override ????public?void?onItemSelected(AdapterView?parent,?View?view,?int?position,?long?id)?{ ????????textView.setText(spinner.getItemAtPosition(position).toString()); ????} ????@Override ????public?void?onNothingSelected(AdapterView?parent)?{ ????????Toast.makeText(mContext,"NotingSelected",Toast.LENGTH_SHORT); ????} ????private?List<Map>?getData(){ ????????Mapmap?=?new?HashMap(); ????????map.put("text","上海"); ????????map.put("pic",R.mipmap.ic_launcher); ????????data_list.add(map); ????????map?=?new?HashMap(); ????????map.put("text","北京"); ????????map.put("pic",R.mipmap.ic_launcher); ????????data_list.add(map); ????????map?=?new?HashMap(); ????????map.put("text","深圳"); ????????map.put("pic",R.mipmap.ic_launcher); ????????data_list.add(map); ????????map?=?new?HashMap(); ????????map.put("text","廣州"); ????????map.put("pic",R.mipmap.ic_launcher); ????????data_list.add(map); ????????return?data_list; ????} }
item.xml