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

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


1.布局activity_spinner.xml

xml version="1.0" encoding="utf-8"?>
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">
    
        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" />


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


xml version="1.0" encoding="utf-8"?>

    <string-array name="provarray">
        北京市
        保定市
        天津市
        深圳市
    string-array>


下面在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();
        }
    }
}


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


android 如何使用spinner来实现选择省份和市区功能_第1张图片


以上就是实现的效果;


谢谢!

你可能感兴趣的:(android,研发)