Android学习笔记之控件Spinner
1.mian.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="vertical" > 6 7 <TextView 8 android:id="@+id/textView1" 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" 11 android:text="你输入的是阿森纳" 12 android:textSize="20sp"/> 13 14 <Spinner 15 android:id="@+id/spinner1" 16 android:layout_marginTop="10dp" 17 android:layout_width="match_parent" 18 android:layout_height="wrap_content"/> 19 20 21 </LinearLayout>
2.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 7 <ImageView 8 android:id="@+id/imageView1" 9 android:layout_width="60dp" 10 android:layout_height="60dp" 11 android:src="@drawable/a"/> 12 13 <TextView 14 android:id="@+id/textView2" 15 android:layout_width="match_parent" 16 android:layout_height="60dp" 17 android:text="阿森纳" 18 android:textSize="20sp" 19 android:gravity="center"/> 20 21 22 </LinearLayout>
3.java代码
1 public class MainActivity extends Activity { 2 3 private TextView tv1; 4 private Spinner s1; 5 private List<Map<String,Object>> dataList; 6 private SimpleAdapter sa; 7 private int[] pic = {R.drawable.a,R.drawable.l,R.drawable.m,R.drawable.q}; 8 private String[] name = {"阿森纳","利物浦","曼联","切尔西"}; 9 10 @Override 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.main); 14 15 tv1 = (TextView) findViewById(R.id.textView1); 16 s1 = (Spinner) findViewById(R.id.spinner1); 17 18 dataList = new ArrayList<Map<String,Object>>(); 19 20 //新建适配器 21 sa = new SimpleAdapter(this, getData(), R.layout.item, new String[]{"pic","name"}, new int[]{R.id.imageView1,R.id.textView2}); 22 23 //设置一个下拉的样式表 24 sa.setDropDownViewResource(R.layout.item); 25 s1.setAdapter(sa); 26 27 //s1设置监听器 28 s1.setOnItemSelectedListener(new OnItemSelectedListener() { 29 30 @Override 31 public void onItemSelected(AdapterView<?> parent, View view, 32 int position, long id) { 33 // TODO Auto-generated method stub 34 String team = sa.getItem(position).toString(); 35 tv1.setText("你输入的是"+team); 36 } 37 38 @Override 39 public void onNothingSelected(AdapterView<?> parent) { 40 // TODO Auto-generated method stub 41 42 } 43 }); 44 } 45 //设置数据源 46 private List<Map<String,Object>> getData(){ 47 for(int i = 0;i<pic.length;i++){ 48 Map<String, Object> map = new HashMap<String, Object>(); 49 map.put("pic",pic[i]); 50 map.put("name", name[i]); 51 dataList.add(map); 52 } 53 return dataList; 54 } 55 56 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。