實現二級列表雙listview省市選擇
阿新 • • 發佈:2019-01-01
實現的效果圖如下
其中 難點在於 xml 的解析,以及兩個listview 的互動
解析xml
public class XmlParserHandler extends DefaultHandler { /** * 儲存所有的解析物件 */ private List<ProvinceModel> provinceList = new ArrayList<ProvinceModel>(); public XmlParserHandler() { } public List<ProvinceModel> getDataList() { return provinceList; } @Override public void startDocument() throws SAXException { // 當讀到第一個開始標籤的時候,會觸發這個方法 } ProvinceModel provinceModel = new ProvinceModel(); CityModel cityModel = new CityModel(); @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // 當遇到開始標記的時候,呼叫這個方法 if (qName.equals("province")) { provinceModel = new ProvinceModel(); provinceModel.setName(attributes.getValue(0)); provinceModel.setCityList(new ArrayList<CityModel>()); } else if (qName.equals("city")) { cityModel = new CityModel(); cityModel.setName(attributes.getValue(0)); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // 遇到結束標記的時候,會呼叫這個方法 if (qName.equals("city")) { provinceModel.getCityList().add(cityModel); } else if (qName.equals("province")) { provinceList.add(provinceModel); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { } }
兩個listView 資料互動
mainlist.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectSE=position;
initAdapter(mCitisDatasMap.get(mProvinceDatas[position]));
mainAdapter.setSelectItem(position);
mainAdapter.notifyDataSetChanged();
}
});
morelist.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(context.getActivity(), mProvinceDatas[selectSE]+mCitisDatasMap.get(mProvinceDatas[selectSE])[position], 0).show();
moreAdapter.setSelectItem(position);
moreAdapter.notifyDataSetChanged();
context.setCityName(mCitisDatasMap.get(mProvinceDatas[selectSE])[position]);
SelectCity.this.dismiss();
}
});
}