【Android学习笔记】Spinner

 注:本笔记英文原版就在你的电脑中: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.

 

6.现在MyOnItemSelectedListener 需要被应用于Spinner了,在onCreate()方法的最后加入下列代码:

7.运行程序,下面是运行结果:

 

 

 

附:以下是我.java中全部代码,仅供参考:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值