android 如何使用spinner来实现选择省份和市区功能

来源:互联网 发布:淘宝网怎么用微信支付 编辑:程序博客网 时间:2024/04/25 14:10

 在项目中开发时遇见市区选择,下面采用spinner来实现,为此做个记录;


1.布局activity_spinner.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"    tools:context=".SpinnerActivity">    <Spinner        android:id="@+id/province"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:entries="@array/provarray" /></RelativeLayout>


2.添加数据源,定义在values包底下,province.xml


<?xml version="1.0" encoding="utf-8"?><resources>    <string-array name="provarray">        <item>北京市</item>        <item>保定市</item>        <item>天津市</item>        <item>深圳市</item>    </string-array></resources>


下面在activity里进行实现;


public class SpinnerActivity extends Activity {    //声明Spinner对象    private Spinner spinProvince=null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_spinner);        //获取Spinner        spinProvince=(Spinner)super.findViewById(R.id.province);        //注册OnItemSelected事件        spinProvince.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) new ProvOnItemSelectedListener());        //获取y下标,设置当前位置        spinProvince.setY(120);        spinProvince.setX(120);    }    //OnItemSelected监听器    private class  ProvOnItemSelectedListener implements AdapterView.OnItemSelectedListener {        @Override        public void onItemSelected(AdapterView<?> adapter,View view,int position,long id) {            //获取选择的项的值            String sInfo=adapter.getItemAtPosition(position).toString();            switch (position){                case 0:                    //获取当前下标,处理自己要做的事情;                   //………                    break;            }            Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();        }        @Override        public void onNothingSelected(AdapterView<?> arg0) {            String sInfo="什么也没选!";            Toast.makeText(getApplicationContext(),sInfo, Toast.LENGTH_LONG).show();        }    }}


用一个截图来看一下效果;




以上就是实现的效果;


谢谢!

阅读全文
1 0
原创粉丝点击