Android spinner三级连动菜单实现核心代码

“`
package com.l000phone.day05_spinnerexercise3;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.l000phone.entity.Province;
import com.l000phone.util.CityWeatherParse;

public class MainActivity extends Activity {
private Spinner sp_province_id;// 省份信息显示下拉列表框控件
private Spinner sp_city_id;// 市级信息显示下拉列表框控件
private Spinner sp_county_id;// 县级信息显示下拉列表框控件

private ArrayAdapter<String> provinceAdapter;
private ArrayAdapter<String> cityAdapter;
private ArrayAdapter<String> countyAdapter;

private String provinceName;// 选中的省份名
private Set<String> address;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // 思路:
    // ①界面控件对象的获取
    sp_province_id = (Spinner) findViewById(R.id.sp_province_id);
    sp_city_id = (Spinner) findViewById(R.id.sp_city_id);
    sp_county_id = (Spinner) findViewById(R.id.sp_county_id);

    // ②准备数据源
    XmlPullParser parser = getResources().getXml(R.xml.citys_weather);
    List<Province> provinces = CityWeatherParse.getProvincesInfo(parser);
    address = new LinkedHashSet<>();

    // ③获得适配器对象
    provinceAdapter = new ArrayAdapter<>(this,
            android.R.layout.simple_spinner_dropdown_item,
            CityWeatherParse.getAllProvinceNames(provinces));

    cityAdapter = new ArrayAdapter<>(this,
            android.R.layout.simple_spinner_dropdown_item);

    countyAdapter = new ArrayAdapter<>(this,
            android.R.layout.simple_spinner_dropdown_item);

    // ④将适配器与Spinner控件进行绑定
    sp_province_id.setAdapter(provinceAdapter);
    sp_city_id.setAdapter(cityAdapter);
    sp_county_id.setAdapter(countyAdapter);

    // ⑤给Spinner下拉列表控件添加监听器(只需要给省份信息显示下拉列表框添加监听器即可)
    OnItemSelectedListener listener = new MyOnItemSelectedListener(
            provinces);
    sp_province_id.setOnItemSelectedListener(listener);
    sp_city_id.setOnItemSelectedListener(listener);
    sp_county_id.setOnItemSelectedListener(listener);
    sp_city_id.setSelection(0);

}

// 监听器OnItemSelectedListener实现类
private final class MyOnItemSelectedListener implements
        OnItemSelectedListener {
    private List<Province> provinces;

    public MyOnItemSelectedListener(List<Province> provinces) {
        super();
        this.provinces = provinces;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.widget.AdapterView.OnItemSelectedListener#onItemSelected(
     * android.widget.AdapterView, android.view.View, int, long)
     */
    @Override
    public void onItemSelected(AdapterView<?> parent, View view,
            int position, long id) {
        address.add(((TextView)view).getText().toString());

        // 思路:
        // ①根据选中的省份信息,将该省份对应的所有市级信息读取出来,设置到cityAdapter中
        // ②根据选中的市级信息,将该市对应的所有县级信息读取出来,设置到countyAdapter中
        String cityName;

        switch (parent.getId()) {
        case R.id.sp_province_id:
            // -->修改市级适配器
            // a)获取省份的名字
            provinceName = ((TextView) view).getText().toString();

            // b)将省份对应的所有市读取取出来
            List<String> allCities = CityWeatherParse.getAllCityNames(// 在这儿用 就相当于 是 局部变量喽
                    provinceName, provinces);

            // c)修改适配器,并通知控件刷新
            cityAdapter.clear();
            cityAdapter.addAll(allCities);
            cityAdapter.notifyDataSetChanged();

            // 更新县级适配器操作
            cityName = allCities.get(0);
            modifyCountyAdapter(cityName);
            MainActivity.this.setTitle("您的籍贯是:"+address.toString());
            break;
        case R.id.sp_city_id:
            // 获取市的名字
            cityName = ((TextView) view).getText().toString();
            Log.i("PROVINCE_NAME", provinceName);
            // 更新县级适配器操作
            modifyCountyAdapter(cityName);
            MainActivity.this.setTitle("您的籍贯是:"+address.toString());
            break;
        case R.id.sp_county_id:
            MainActivity.this.setTitle("您的籍贯是:"+address.toString());
            address.clear();
            break;

        default:
            break;
        }


    }

    /**
     * @param view
     */
    private void modifyCountyAdapter(String cityName) {

        // b)将市对应的所有县读取取出来
        List<String> allCounties = CityWeatherParse.getAllCountyames(
                cityName, provinceName, provinces);

        // c)修改适配器,并通知控件刷新
        countyAdapter.clear();
        countyAdapter.addAll(allCounties);
        countyAdapter.notifyDataSetChanged();
        sp_county_id.setSelection(0);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.widget.AdapterView.OnItemSelectedListener#onNothingSelected
     * (android.widget.AdapterView)
     */
    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

}

}

“`util

/** * */
package com.l000phone.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

import com.l000phone.entity.City;
import com.l000phone.entity.County;
import com.l000phone.entity.Province;

/** * Description: 城市天气情况解析<br/> * Copyright (c) , 2016, Jansonxu <br/> * This program is protected by copyright laws. <br/> * Program Name:CityWeatherParse.java <br/> * Date: 2016-2-17 * * @author ly * @version : 1.0 */
public class CityWeatherParse {

    /** * 获取所有省份的名字 * * @param provinces * @return */
    public static List<String> getAllProvinceNames(List<Province> provinces) {
        List<String> allNames = new LinkedList<>();
        for (Province Provice : provinces) {
            allNames.add(Provice.getPn());
        }

        return allNames;
    }

    /** * * @param parser * @return */
    public static List<Province> getProvincesInfo(XmlPullParser parser) {
        // 思路
        @SuppressWarnings("unused")
        InputStream is = null;
        List<Province> provinces = null;// 存放所有的省份信息
        try {

            // 解析
            int eventType = parser.getEventType();
            Province province = null;// 省份实例声明
            City city = null;// 城市实例的声明
            County county = null;// 县实例的声明

            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = parser.getName();

                switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    System.out.println("xml解析开始...");
                    provinces = new LinkedList<>();
                    break;
                case XmlPullParser.START_TAG:
                    if ("p".equals(nodeName)) {
                        province = new Province();// 省份实例的构建
                        // 将p节点的属性设置到Province实例中
                        setInstanceAttrValue(parser, province);
                    } else if ("pn".equals(nodeName)) {
                        province.setPn(parser.nextText());
                    } else if ("c".equals(nodeName)) {
                        city = new City();// 城市实例的构建
                        // 将c节点的属性设置到City实例中
                        setInstanceAttrValue(parser, city);
                    } else if ("cn".equals(nodeName)) {
                        city.setCn(parser.nextText());
                    } else if ("d".equals(nodeName)) {
                        county = new County();
                        setInstanceAttrValue(parser, county);
                        county.setDn(parser.nextText());

                        // 应该将其添加到City中
                        city.getCounties().add(county);
                    }

                    break;
                case XmlPullParser.END_TAG:
                    if ("c".equals(nodeName)) {
                        province.getCities().add(city);
                    } else if ("p".equals(nodeName)) {
                        provinces.add(province);
                    }

                    break;
                }
                eventType = parser.next();

            }

            System.out.println("xml解析结束...");
            // ④分析解析后的结果
            System.out.println("xml文件解析的结果是:");
            for (Province p : provinces) {
                System.out.println(p);
            }

        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // ⑤释放资源
            return provinces;
        }

    }

    /** * 设置实例的属性值 * * @param parser * @param obj */
    private static void setInstanceAttrValue(XmlPullParser parser, Object obj) {
        for (int index = 0; index < parser.getAttributeCount(); index++) {
            String attrName = parser.getAttributeName(index);
            String attrValue = parser.getAttributeValue(index);
            if ("p_id".equals(attrName)) {
                ((Province) obj).setP_id(attrValue);
            } else if ("c_id".equals(attrName)) {
                ((City) obj).setC_id(attrValue);
            } else if ("d_id".equals(attrName)) {
                ((County) obj).setD_id(attrValue);
            }
        }
    }

    /** * 根据传入的省份名,获取该省份下所有的市名 * * @param provinceName * @param provinces * @return */
    public static List<String> getAllCityNames(String provinceName,
            List<Province> provinces) {
        List<String> cityNames = new LinkedList<>();

        for (Province province : provinces) {
            if (provinceName != null && provinceName.equals(province.getPn())) {
                for (City city : province.getCities()) {
                    cityNames.add(city.getCn());
                }
                break;
            }
        }

        return cityNames;
    }

    /** * 根据传入的省份名、城市名,获得该城市下所有的县名 * * @param cityName * @param provinceName * @param provinces * @return */
    public static List<String> getAllCountyames(String cityName,
            String provinceName, List<Province> provinces) {
        List<String> countyNames = new LinkedList<>();

        EXIT_FLG: for (Province provice : provinces) {
            if (provinceName != null && provinceName.equals(provice.getPn())) {
                for (City city : provice.getCities()) {
                    if (cityName != null && cityName.equals(city.getCn())) {
                        for (County county : city.getCounties()) {
                            countyNames.add(county.getDn());
                        }
                        break EXIT_FLG;
                    }

                }
            }
        }

        Log.i("PROVINCE_NAME", "countyNames = " + countyNames + ",cityName = "
                + cityName + ",provinces=" + provinces);
        return countyNames;
    }

}

entity

/** * */
package com.l000phone.entity;

import java.util.LinkedList;
import java.util.List;

/** * Description: 地级市实体类<br/> * Copyright (c) , 2016, Jansonxu <br/> * This program is protected by copyright laws. <br/> * Program Name:City.java <br/> * Date: 2016-2-17 * * @authorly * @version : 1.0 */
public class City {
    private String c_id;// 城市的id
    private String cn;// 城市名字
    private List<County> counties = new LinkedList<>();// 多个县,县级市

    public City() {
        super();
    }

    public City(String c_id, String cn, List<County> counties) {
        super();
        this.c_id = c_id;
        this.cn = cn;
        this.counties = counties;
    }

    public String getC_id() {
        return c_id;
    }

    public void setC_id(String c_id) {
        this.c_id = c_id;
    }

    public String getCn() {
        return cn;
    }

    public void setCn(String cn) {
        this.cn = cn;
    }

    public List<County> getCounties() {
        return counties;
    }

    public void setCounties(List<County> counties) {
        this.counties = counties;
    }

    @Override
    public String toString() {
        return "City [c_id=" + c_id + ", cn=" + cn + ", counties=" + counties
                + "]";
    }

}

/**
*
*/
package com.l000phone.entity;

/**
* Description: 县(县级市)实体类

* Copyright (c) , 2016, Jansonxu

* This program is protected by copyright laws.

* Program Name:County.java

* Date: 2016-2-17
*
* @author ly
* @version : 1.0
*/
public class County {
private String d_id;// 县的id
private String dn;// 县名

public County() {
    super();
}

public County(String d_id, String dn) {
    super();
    this.d_id = d_id;
    this.dn = dn;
}

public String getD_id() {
    return d_id;
}

public void setD_id(String d_id) {
    this.d_id = d_id;
}

public String getDn() {
    return dn;
}

public void setDn(String dn) {
    this.dn = dn;
}

@Override
public String toString() {
    return "County [d_id=" + d_id + ", dn=" + dn + "]";
}

}

/**
*
*/
package com.l000phone.entity;

import java.util.LinkedList;
import java.util.List;

/**
* Description: 省份实体类

* Copyright (c) , 2016, Jansonxu

* This program is protected by copyright laws.

* Program Name:Province.java

* Date: 2016-2-17
*
* @author ly
* @version : 1.0
*/
public class Province {
private String p_id;// 省份id
private String pn;// 省份名字
private List cities = new LinkedList<>();// 多个地级市

public Province() {
    super();
}

public Province(String p_id, String pn, List<City> cities) {
    super();
    this.p_id = p_id;
    this.pn = pn;
    this.cities = cities;
}

public String getP_id() {
    return p_id;
}

public void setP_id(String p_id) {
    this.p_id = p_id;
}

public String getPn() {
    return pn;
}

public void setPn(String pn) {
    this.pn = pn;
}

public List<City> getCities() {
    return cities;
}

public void setCities(List<City> cities) {
    this.cities = cities;
}

@Override
public String toString() {
    return "Province [p_id=" + p_id + ", pn=" + pn + ", cities=" + cities
            + "]";
}

}

“`

你可能感兴趣的:(Spinner,二级缓存)