1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:orientation="vertical" 4 android:layout_height="fill_parent" 5 android:layout_width="fill_parent"> 6 <Spinner 7 android:id="@+id/spinner1" 8 android:layout_width="fill_parent" 9 android:layout_height="wrap_content"/> 10 <Spinner 11 android:id="@+id/spinner2" 12 android:layout_width="fill_parent" 13 android:layout_height="wrap_content"/> 14 </LinearLayout>
在item.xml文件中:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="horizontal" > 6 <ImageView android:id="@+id/imageview" android:layout_width="60dp" 7 android:layout_height="60dp" android:src="@drawable/ic_launcher" 8 android:paddingLeft="10dp"></ImageView> 9 <TextView android:id="@+id/textview" android:textColor="#000" 10 android:layout_width="wrap_content" android:layout_height="fill_parent" 11 android:textSize="16dp" android:gravity="center_vertical" 12 android:paddingLeft="10dp"></TextView> 13 </LinearLayout>
在.java文件中:
1 private Spinner spinner; 2 private Spinner spinner2; 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.main); 7 spinner = (Spinner) findViewById(R.id.spinner1); 8 ArrayAdapter< String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, new String[]{"aa","bb","cc","dd"}); 9 spinner.setAdapter(adapter); //android系统中自带布局 10 11 spinner2 =(Spinner) findViewById(R.id.spinner2); 12 final List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); 13 Map<String, Object > map = new HashMap<String, Object>(); 14 map.put("name", "girl1"); 15 map.put("image", R.drawable.gril1); 16 data.add(map); 17 map = new HashMap<String, Object>(); 18 map.put("name", "girl2"); 19 map.put("image", R.drawable.gril2);//将图片id地址加载到map中,布局中的imageview会自动显示对应图片 20 data.add(map); 21 map = new HashMap<String, Object>(); 22 map.put("name", "gir3"); 23 map.put("image", R.drawable.gril3); 24 data.add(map); 25 SimpleAdapter adapter2 = new SimpleAdapter(MainActivity.this, data,R.layout.item, new String[]{"image","name"}, new int[]{R.id.imageview,R.id.textview}); 26 spinner2.setAdapter(adapter2); //自定义布局 27 spinner2.setOnItemSelectedListener(new OnItemSelectedListener() { 28 29 @Override 30 public void onItemSelected(AdapterView<?> parent, View view, 31 int position, long id) { 32 // TODO 自动生成的方法存根 33 Map<String, Object> item = data.get(position); 34 setTitle(item.get("name").toString()); 35 } 36 37 @Override 38 public void onNothingSelected(AdapterView<?> parent) { 39 // TODO 自动生成的方法存根 40 41 } 42 }); 43 }
运行结果:
原文:http://www.cnblogs.com/SoulCode/p/5405843.html