Spinner

SpinnerActivity:

 1 import android.app.Activity;
2 import android.os.Bundle;
3 import android.view.View;
4 import android.widget.AdapterView;
5 import android.widget.AdapterView.OnItemSelectedListener;
6 import android.widget.ArrayAdapter;
7 import android.widget.Spinner;
8 import android.widget.TextView;
9
10 public class SpinnerActivity extends Activity
11 {
12 private TextView mTextView;
13
14 private Spinner mSpinner;
15
16 private ArrayAdapter<String> adapter;
17
18 private static final String[] mCounties = {"O型", "A型", "B型", "AB型", "其他"};
19
20 @Override
21 public void onCreate(Bundle savedInstanceState)
22 {
23 super.onCreate(savedInstanceState);
24 setContentView(R.layout.main);
25 mTextView = (TextView) findViewById(R.id.textView);
26 mSpinner = (Spinner) findViewById(R.id.spinner);
27 // 将可选内容与ArraryAdapter连接
28 adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mCounties);
29
30 // 设置下拉列表的风格
31 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
32
33 // 将adapter添加到mSpinner中
34 mSpinner.setAdapter(adapter);
35
36 // 添加Spinner事件监听
37 mSpinner.setOnItemSelectedListener(listener);
38 }
39
40 OnItemSelectedListener listener = new OnItemSelectedListener()
41 {
42
43 @Override
44 public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
45 {
46 mTextView.setText("你的血型是:" + mCounties[position]);
47 // 设置显示当前项
48 parent.setVisibility(View.VISIBLE);
49 }
50
51 @Override
52 public void onNothingSelected(AdapterView<?> parent)
53 {
54 }
55 };
56 }

 

Layout/main.xml:

 

 1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical"
4 android:layout_width="fill_parent"
5 android:layout_height="fill_parent"
6 >
7 <TextView
8 android:id="@+id/textView"
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 />
12 <Spinner
13 android:id="@+id/spinner"
14 android:layout_width="wrap_content"
15 android:layout_height="wrap_content"
16 android:layout_centerHorizontal="true"
17 />
18 </LinearLayout>

 

2.效果图:



posted @ 2011-10-30 15:40  程序学习笔记  阅读(273)  评论(0编辑  收藏  举报