[Android] Spinners介绍及用法
本文地址:http://www.cnblogs.com/rossoneri/p/4366018.html
Spinners介绍
Spinners提供了从一个集(set)中选择某个值(value)的一个快速的方法。在缺省状态,一个spinner显示它当前选择的一个值。触摸spinner会显示一个含有所有其他有效值的下拉菜单,用户可以从中选择一个新值。

你可以使用 Spinner 对象在布局中添加一个 spinner。你应该在你的XML布局文件中使用 <Spinner> 元素来添加。比如:
<Spinner
android:id="@+id/planets_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
为了用一个选项列表填充(populate) spinner,你需要在你的 Activity 或者 Fragment 源码中指定(specify)一个 SpinnerAdapter。
用用户的选项来填充Spinner(Populate the Spinner with User Choices)
你可以使用任何来源的选项来填充spinner,但一定要通过一个SpinnerAdapter来提供,比如一个ArrayAdapter,如果那些从数据库查询出来的选项是可用的,保存在一个array或者一个CursorAdapter里且有效的话。
比如说,如果那些用来填充spinner的有效选项是预先确定好的,你可以用一个在资源文件中定义好的数组来提供选项:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
使用像这样的数组,你可以在你的 Activity 或者 Fragment 用以下代码借助一个 ArrayAdapter 的实例来为 spinner 提供数据:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
createFromResource() 方法允许你从一个 string array 中创建一个 ArrayAdapter。其第三个参数是一个定义了被选中的选项如何在 spinner 控件中显示的布局资源。simple_spinner_item 是一个平台提供的布局,也是你应该用的默认布局,除非你希望定义自己的 spinner 外观。
之后你要调用 setDropDownViewResource(int) 来指定 spinner 显示下拉选项的布局样式(simple_spinner_dropdown_item 是另一个平台提供的标准布局)。
调用 setAdapter() 把你的 adapter 应用到 Spinner。
用户选择的响应(Responding to User Selections)
当用户从下拉菜单选择了一项内容, Spinner 对象接收到一个 on-item-selected 的事件。
为 spinner 定义一个选择事件的处理方法,实现 AdapterView.OnItemSelectedListener 接口和对应的(corresponding) onItemSelected() 回调方法。比如:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
AdapterView.OnItemSelectedListener 要求 onItemSelected() 和 onNothingSelected() 回调方法。
然后你需要调用 setOnItemSelectedListener 指定接口的实现 (specify the interface implementation):
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
如果你在你的 Activity 或者 Fragment 实现 AdapterView.OnItemSelectedListener 接口(就像上面的例子),你可以传递 this 作为接口实例。
Spinner类需要了解的内容
public class Spinner extends AbsSpinner implements DialogInterface.OnClickListener
| Attribute Name | Related Method | Description |
| android:dropDownHorizontalOffset | setDropDownHorizontalOffset(int) | Amount of pixels by which the drop down should be offset horizontally. |
| android:dropDownSelector | List selector to use for spinnerMode="dropdown" display. | |
| android:dropDownVerticalOffset | setDropDownVerticalOffset(int) | Amount of pixels by which the drop down should be offset vertically. |
| android:dropDownWidth | setDropDownWidth(int) | Width of the dropdown in spinnerMode="dropdown". |
| android:gravity | setGravity(int) | Gravity setting for positioning the currently selected item. |
| android:popupBackground | setPopupBackgroundResource(int) | Background drawable to use for the dropdown in spinnerMode="dropdown". |
| android:prompt | The prompt to display when the spinner's dialog is shown. | |
| android:spinnerMode | Display mode for spinner options. |
| int | MODE_DIALOG | Use a dialog window for selecting spinner options. |
| int | MODE_DROPDOWN | Use a dropdown anchored to the Spinner for selecting spinner options. |
其他的一些方法就不列了,用什么查什么好了。
简单的例子
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.android_spinner.MainActivity" > <TextView
android:id="@+id/testview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/main_city" /> <Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> </LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources> <string name="app_name">Android_spinner</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="main_city">Choose your city : %1$s</string> </resources>
MainActivity.java
package com.example.android_spinner; import java.util.ArrayList;
import java.util.List; import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView; public class MainActivity extends Activity { private Spinner mSpinner;
private TextView mTextview;
private List<String> cities = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private String mStr; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); initData();
initEvent();
} private void initData() {
mStr = getResources().getString(R.string.main_city);
// 添加spinner列表项
cities.add("Beijing");
cities.add("Shanghai");
cities.add("Guangzhou");
cities.add("Shenzhen");
cities.add("Nanjing"); mTextview = (TextView) findViewById(R.id.testview);
mSpinner = (Spinner) findViewById(R.id.spinner); String str = String.format(mStr, cities.get(0));
mTextview.setText(str); // 为下拉列表创建adapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cities); // 为adapter设置下拉菜单样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // spinner设置adapter
mSpinner.setAdapter(adapter); } private void initEvent() {
// 添加spinner事件
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String str = String.format(mStr, adapter.getItem(position));
mTextview.setText(str); parent.setVisibility(View.VISIBLE);
} @Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
mTextview.setText("None selected");
parent.setVisibility(View.VISIBLE);
}
}); } @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
效果:

参考
[Android] Spinners介绍及用法的更多相关文章
- 怎么通过activity里面的一个按钮跳转到另一个fragment(android FragmentTransaction.replace的用法介绍)
即:android FragmentTransaction.replace的用法介绍 Fragment的生命周期和它的宿主Activity密切相关,几乎和宿主Activity的生命周期一致,他们之间最 ...
- android的logcat详细用法
Android日志系统提供了记录和查看系统调试信息的功能.日志都是从各种软件和一些系统的缓冲区中记录下来的,缓冲区可以通过 logcat 命 令来查看和使用. 使用logcat命令 你可以用 logc ...
- Android monkey介绍
Android monkey介绍 原文地址 1 简略 monkey是android下自动化测试比较重要的的一个工具,该工具可以运行在host端或者设备(模拟器或真实设备).它会向系统发送随机事件流(即 ...
- android动画介绍之 自定义Animation动画实现qq抖一抖效果
昨天我们介绍了Animation的基本用法.小伙伴们了解的怎么样了?如果还没有了解过Animation的小伙伴可以看看这篇博客 android动画介绍--Animation 实现loading动画效果 ...
- android Animation介绍
Animation介绍: 在Android SDK介绍了2种Animation模式: 1. Tween Animation:间动画,通过对场景里的对象不断做图像变换(平移.缩放.旋转)产生动画效果,即 ...
- android AsyncTask介绍(转)
android AsyncTask介绍 AsyncTask和Handler对比 1 ) AsyncTask实现的原理,和适用的优缺点 AsyncTask,是android提供的轻量级的异步类,可以直接 ...
- Android开发中Bundle用法包裹数据(转)
Android开发中Bundle用法包裹数据 Bundle的经典用法,包裹数据放入Intent中,目的在于传输数据. SDK 里是这样描述: A mapping from String values ...
- 【转】Android各种Adapter的用法
转自:http://my.oschina.net/u/658933/blog/372151 Android各种Adapter的用法 发表于5个月前(2015-01-27 10:56) 阅读(143 ...
- oc-12-NSString 类简单介绍及用法
// 11-[掌握]NSString 类简单介绍及用法 #import <Foundation/Foundation.h> int main(int argc, const char * ...
随机推荐
- vue2打包时内存溢出解决方案
vue项目完成时,若项目过大,就会出现内存溢出的问题,导致vue打包不成功 错误截图 解决方案 在依赖package.json中修改build为 "build":"nod ...
- vector源码(参考STL源码--侯捷):空间分配导致迭代器失效
vector源码1(参考STL源码--侯捷) vector源码2(参考STL源码--侯捷) vector源码(参考STL源码--侯捷)-----空间分配导致迭代器失效 vector源码3(参考STL源 ...
- [Python学习笔记-002] lambda, map, filter and reduce
1. lambda lambda, 即匿名函数,可以理解为跟C语言的宏类似.例如: >>> max = lambda x, y: x if x > y else y >& ...
- Python虚拟环境工具-Virtualenv 介绍及部署记录
在开发Python应用程序时,系统默认的Python版本可能会不兼容这个应用程序, 如果同时开发多个应用程序, 可能会用到好几个版本的python环境, 这种情况下,每个应用可能需要各自拥有一套&qu ...
- redis乐观锁(适用于秒杀系统)
redis事务中的WATCH命令和基于CAS的乐观锁 在Redis的事务中,WATCH命令可用于提供CAS(check-and-set)功能.假设我们通过WATCH命令在事务执行之前监控了多个Key ...
- 使用area标签模仿a标签
众所周知,map标签可以给img图像标记热点区域,而area标签就是跟map标签一起使用的. 但area标签的作用可不止用来标记热点,因为它也有href属性,因此某些场景可以代替a标签进行页面跳转. ...
- HDU 1576 A/B(欧几里德算法延伸)
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1576 题目: Problem Description 要求(A/B)%9973,但由于A很大,我们只 ...
- 1.1 PIL:Python图像处理类库
from PIL import Image img = Image.open('Husky.jpg') # 看看这货长什么样子 img # 看看它的大小 print('The size of this ...
- C编程基础
1. Hello World! 依照惯例首先Hello World镇楼: 1 #include<stdio.h> 2 3 int main(void) { 4 printf("H ...
- 安装mysql时报Missing required library libcc.dll 126
Missing required library libcc.dll 126 安装一个Cygwin就好了