欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【达内课程】xml实现省份联动

程序员文章站 2022-03-26 13:16:40
...

效果图

【达内课程】xml实现省份联动

提前预习

https://blog.csdn.net/u010356768/article/details/81938244
https://blog.csdn.net/u010356768/article/details/81973981

代码

provinces.xml

<Provinces>
   <Province ID="1" ProvinceName="北京市">北京市</Province>
   <Province ID="2" ProvinceName="天津市">天津市</Province>
   <Province ID="3" ProvinceName="河北省">河北省</Province>
   <Province ID="4" ProvinceName="山西省">山西省</Province>
   <Province ID="5" ProvinceName="内蒙古自治区">内蒙古自治区</Province>
</Provinces>

cities.xml

<Cities>
   <City ID="1" CityName="北京" PID="1" ZipCode="100000">北京</City>
   <City ID="2" CityName="天津" PID="2" ZipCode="100000">天津</City>
   <City ID="3" CityName="石家庄" PID="3" ZipCode="050000">石家庄</City>
   <City ID="4" CityName="唐山" PID="3" ZipCode="063000">唐山</City>
   <City ID="5" CityName="秦皇岛" PID="3" ZipCode="066000">秦皇岛</City>
   <City ID="14" CityName="太原" PID="4" ZipCode="030000">太原</City>
   <City ID="15" CityName="大同" PID="1" ZipCode="037000">大同</City>
   <City ID="25" CityName="呼和浩特" PID="5" ZipCode="010000">呼和浩特</City>
</Cities>

Province.java来描述一个省份

public class Province {
    private int id;
    private String name;

    public Province() {
    }

    public Province(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return this.name;
    }
}

City.java来描述一个城市

public class City {
    private int id;
    private int pid;
    private String name;

    public City() {
    }

    public City(int id, int pid, String name) {
        this.id = id;
        this.pid = pid;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getPid() {
        return pid;
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return this.name;
    }
}

布局文件activity_main.xml

<LinearLayout 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"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="300dp">
        <ListView
            android:id="@+id/lvProvince"
            android:layout_width="0dp"
            android:layout_height="300dp"
            android:layout_weight="1"
            />
        <ListView
            android:id="@+id/lvCity"
            android:layout_width="0dp"
            android:layout_height="300dp"
            android:layout_weight="1"
            />
    </LinearLayout>

</LinearLayout>

MainActivity

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Xml;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xmlpull.v1.XmlPullParser;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private ListView lvProvince;
    private ListView lvCity;
    List<Province> provinces;
    private List<City> allCities;
    private List<City> cities = new ArrayList<City>();

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

        setViews();

        try {
            //解析省份的xml
            parseAndLoadProvince();
            parseCity();
        } catch (Exception e) {
            e.printStackTrace();
        }

        setListeners();
    }


    /**
     * 设置监听
     */
    private void setListeners() {
        lvProvince.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //获取当前选中的是哪个省份
                Province p = provinces.get(i);
                int pid = p.getId();
                //遍历allCities 过滤所有需要的城市数据
                cities.clear();
                for(City c:allCities){
                    if(c.getPid() == pid){
                        cities.add(c);
                    }
                }
                //更新adapter
                ArrayAdapter<City> city = new ArrayAdapter<City>(MainActivity.this,android.R.layout.simple_list_item_1,cities);
                lvCity.setAdapter(city);
            }
        });
    }

    /**
     * 解析所有城市数据并保存到成员变量
     * 适合使用PULL解析
     */
    private void parseCity() throws Exception {
        XmlPullParser parser = Xml.newPullParser();
        InputStream is = getAssets().open("cities.xml");
        parser.setInput(is, "utf-8");
        int type = parser.getEventType();
        allCities = new ArrayList<City>();
        City city = null;
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                //碰到了开始标记
                case XmlPullParser.START_TAG:
                    String name = parser.getName();
                    if (name.equals("City")) {//创建对象
                        city = new City();
                        city.setId(Integer.parseInt(parser.getAttributeValue(0)));
                        city.setName(parser.getAttributeValue(1));
                        city.setPid(Integer.parseInt(parser.getAttributeValue(2)));
                        allCities.add(city);
                    }
                    break;
                default:
                    break;
            }
            type = parser.next();
        }
    }

    /**
     * 解析并加载省份信息(DOM4J)
     */
    private void parseAndLoadProvince() throws Exception {
        SAXReader reader = new SAXReader();
        InputStream is = getAssets().open("provinces.xml");
        Document doc = reader.read(is);
        //获取文档根元素
        Element root = doc.getRootElement();
        List<Element> proEles = root.elements();
        provinces = new ArrayList<Province>();
        for (Element e : proEles) {
            //获取省份ID和省份名称
            String id = e.attributeValue("ID");
            String name = e.attributeValue("ProvinceName");
            Province p = new Province(Integer.parseInt(id), name);
            provinces.add(p);
        }
        //解析完毕,立即显示到界面中
        ArrayAdapter<Province> adapter = new ArrayAdapter<Province>(this, android.R.layout.simple_list_item_1, provinces);
        lvProvince.setAdapter(adapter);
    }

    private void setViews() {
        lvProvince = findViewById(R.id.lvProvince);
        lvCity = findViewById(R.id.lvCity);
    }
}
相关标签: xml