在Android开发中,下拉列表(Spinner)是一种常用的UI组件,用于为用户提供选项选择。本文将通过一个具体的示例,展示如何实现院系与专业下拉列表的联动功能,即用户选择不同的院系时,专业下拉列表会动态更新对应的专业选项。
一、功能需求
我们希望通过两个下拉列表实现以下功能:
-
第一个下拉列表显示院系选项(如“计算机学院”、“软件学院”)。
-
当用户选择一个院系后,第二个下拉列表会根据选中的院系动态更新对应的专业选项(如“计算机学院”对应“计科1班”、“计科2班”等)。
-
提供一个按钮,点击后显示用户选择的院系和专业。
二、代码实现
1. 布局文件(activity_test.xml
)
布局文件定义了两个下拉列表(Spinner
)和一个按钮(Button
),分别用于选择院系、专业和保存选择。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".TestActivity">
<!-- 院系选择 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="院系:&