注:本笔记英文原版就在你的电脑中:X:/Program Files/Android/android-sdk-windows/docs/resources/tutorials/views/hello-spinner.html(X即你安装SDK的盘符。)
本示例下载地址:http://download.csdn.net/source/3038894s
Spinner是一个类似于下拉列表的控件。
在本次学习笔记中,我将创建一个简单的Spinner用于显示一组行星列表。当选中其中一个时,将把先把的项目以吐司消息的形式显示出来。
1.在eclipse中新建一个名为HelloSpinner的Android项目;
2.打开res/layout/main.xml,并插入以为代码:
可以注意到TextView的android:text和Spinner的android:prompt都是指向一个string源。这是什么意思呢?就是这个string源的文字既可用作一个控件的标题,也可以在使用Spinner时,作为选择框弹出时的提示信息。
(TextView的android:text)
Spinner的android:prompt
3. 在res/values/strings.xml中编辑如下:
<string name="planet_prompt">Choose a planet</string>即是main.xml中TextView和Spinner的string源
<string-array>节点中的是用于显示在列表的中各项目。
4.现在打开HelloSpinner.java,并且插入以下代码在onCreate()中:
After the main.xml
layout is set as the content view, the Spinner
widget is captured from the layout with findViewById(int)
. The createFromResource()
method then creates a new ArrayAdapter
, which binds each item in the string array to the initial appearance for the Spinner
(which is how each item will appear in the spinner when selected). The R.array.planets_array
ID references the string-array
defined above and the android.R.layout.simple_spinner_item
ID references a layout for the standard spinner appearance, defined by the platform. Then setDropDownViewResource(int)
is called to define the appearance for each item when the widget is opened (simple_spinner_dropdown_item
is another standard layout defined by the platform). Finally, the ArrayAdapter
is set to associate all of its items with the Spinner
by calling setAdapter(T)
.
5.下面创建一个用于返回吐司消息的代码,和public void onCreate(Bundle savedInstanceState)并列:
The AdapterView.OnItemSelectedListener
requires the onItemSelected()
and onNothingSelected()
callback methods. The former is called when an item from the AdapterView
is selected, in which case, a short Toast
message displays the selected text; and the latter is called when a selection disappears from the AdapterView
, which doesn't happen in this case, so it's ignored.
7.运行程序,下面是运行结果:
附:以下是我.java中全部代码,仅供参考: