零、学习目标
能说出下拉列表的基本用法
能利用下拉列表编写简单安卓应用
一、下拉列表概述
1、继承关系图

Spinner控件显示单列数据,因此只能在程序里采用数组适配器来建立数据源与下拉列表之间的关联。另外,有一种更简单的绑定数据源的方式,直接在布局文件里设置下拉列表元素的entries属性来绑定数组作为数据源。
2、常用属性和方法

二、教学案例——选择测试科目
(一)运行效果

(二)涉及知识点
线性布局(LinearLayout)
标签(TextView)
数组适配器(ArrayAdapter)
吐司(Toast)
(三)实现步骤
1、创建安卓应用【SelectSubject】


2、将背景图片拷贝到drawable目录

3、主布局资源文件activity_main.xml

<?xml version="1.0" encoding="utf-8"?><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:background="@drawable/background"
android:padding="15dp"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvTestSubject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#0000ff"
android:textSize="25sp"
android:text="@string/test_subject"/>
<Spinner
android:id="@+id/spTestSubject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/subjects"/></LinearLayout>
4、字符串资源文件strings.xml

下拉列表 - 选择测试科目
测试科目:
安卓开发
Web开发
数据结构
网络技术
Python编程
形势与政策
5、启动应用,查看效果
通过下拉列表的entries属性绑定好了数据源,此时无须适配器也能看到下拉列表能展开列表项

6、主界面类 - MainActivity

声明变量

通过资源标识符获取控件实例

获取测试科目数组

给下拉列表注册监听器

启动应用,查看效果

8、修改主布局资源文件 - activity_main.xml
不给下拉列表设置entries属性
<?xml version="1.0" encoding="utf-8"?><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:background="@drawable/background"
android:orientation="horizontal"
android:padding="15dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvTestSubject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/test_subject"
android:textColor="#0000ff"
android:textSize="16sp" />
<Spinner
android:id="@+id/spTestSubject"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /></LinearLayout>
9、修改主界面类 - MainActivity

10、启动应用,查看效果

1599

被折叠的 条评论
为什么被折叠?



