【Android组件之Spinner高级功能--级联选择】

本文介绍如何在Android应用中实现省市区级联选择功能。通过Spinner组件并结合自定义监听事件,可以根据用户选择的省份动态更新对应的城市列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、省市区级联操作

Web系统的select下拉列表,可以实现省市区级联操作,选择省出现该省下面的城市,而不是其他省的城市,如下图:


 那么Android系统中的下拉列表组件Spinner能否实现省市区级联呢,答案是肯定的,如下图:



 

 二、Android省市区级联源码如下:

1)界面文件,参考

              

永久链接: http://gaojingsong.iteye.com/blog/2356364

预览文章: 【Android组件之Spinner使用】

                <TextView android:layout_width="fill_parent"

                      android:layout_height="wrap_content" android:text="城市:" />

               <Spinner android:id="@+id/sp" android:layout_width="wrap_content"

                     android:layout_height="wrap_content" android:entries="@array/my_citys"

                     android:prompt="@string/info" />

             <TextView android:layout_width="fill_parent"

                    android:layout_height="wrap_content" android:text="区域:" />

            <Spinner android:id="@+id/areas" android:layout_width="wrap_content"

                  android:layout_height="wrap_content" android:entries="@array/my_areas"

                  android:prompt="@string/info" />

2)级联JAVA代码如下:

         //定义二级列表数组

        private String[][] areas = new  String[][]{{"海淀","朝阳"},{"浦东"},{"广州","东莞","深圳"}};

        Spinner  areasSpinner = (Spinner) this.findViewById(R.id.areas);

        Spinner  spCity = (Spinner) this.findViewById(R.id.sp);

        //注册监听事件

        spCity.setOnItemSelectedListener(new MyCityItemSelectedListener());

 

 

监听核心代码

       private class MyCityItemSelectedListener implements OnItemSelectedListener{

       /**

           parent The AdapterView where the selection happened

          view  The view within the AdapterView that was clicked

          position  The position of the view in the adapter

          id    The row id of the item that is selected

       */

     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

         ArrayAdapter adapter = new ArrayAdapter<String>(HelloActivity.this, 

         android.R.layout.simple_spinner_item, HelloActivity.this.areas[position]);

         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        areasSpinner.setAdapter(adapter);

      }

 

       public void onNothingSelected(AdapterView<?> arg0) {

       }

     }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值