android 实现按照城市首字母(拼音)分类的应用

来源:互联网 发布:node.js bootstrap 编辑:程序博客网 时间:2024/05/16 07:13
最近按照公司需要,写了一个按照城市首字母排序的demo,原理就是获取城市名称,然后将城市名称转换为相应的拼音,通过对拼音的排序进而得到一个序列,实现了按照首字母分类的功能。上代码:

获得城市信息,此处为假数据,大家可以自行添加自己的服务器端数据:

/* * 绑定城市信息,此处为假数据 */public void getcityData(){HashMap<String, Object> hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID, "1");hashcityMap.put(CITYNAME, "青岛");hashcityMap.put(PROVINCEID, "0");//hashcityMap.put(SORT_KEY, getPinyin("青岛"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID,"2");hashcityMap.put(CITYNAME, "济南");hashcityMap.put(PROVINCEID, "0");//hashcityMap.put(SORT_KEY, getPinyin("济南"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID, "3");hashcityMap.put(CITYNAME, "日照");hashcityMap.put(PROVINCEID,"0");//hashcityMap.put(SORT_KEY, getPinyin("日照"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID, "4");hashcityMap.put(CITYNAME, "济宁");hashcityMap.put(PROVINCEID, "0");//hashcityMap.put(SORT_KEY, getPinyin("济宁"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID, "5");hashcityMap.put(CITYNAME, "武汉");hashcityMap.put(PROVINCEID, "1");//hashcityMap.put(SORT_KEY, getPinyin("济宁"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);Collections.sort(arrayList,comparator);}

并且添加完数据后还需要对其进行排序

排序函数Collections.sort(arrayList,comparator);

Comparator<HashMap<String, Object>> comparator = new Comparator<HashMap<String, Object>>() {public int compare(HashMap<String, Object> s1,HashMap<String, Object> s2) {String str1 = s1.get(SORT_KEY).toString();String str2 = s2.get(SORT_KEY).toString();if (str1.compareTo(str2)>0){return 1;}else {return -1;}}};


由于需要添加省的一些信息,此处给出了绑定省的方法

/* * 绑定provinceid到省,此处为假数据 */public void getprovinceData(){provincenameHashMap.put("0", "山东");provincenameHashMap.put("1", "湖北");}

取得完数据之后绑定到apapter上

if (arrayList != null && arrayList.size() > 0) {List<ContentValues> list = new ArrayList<ContentValues>();for (int i = 0; i < arrayList.size(); i++) {HashMap<String, Object> hashMap=new HashMap<String, Object>();hashMap=arrayList.get(i);ContentValues cv = new ContentValues();String cityname = (String)hashMap.get(CITYNAME);Log.e("cityname",cityname);String cityid = (String)hashMap.get(CITYID);String provinceid = (String)hashMap.get(PROVINCEID);String sortKey = (String)hashMap.get(SORT_KEY);cv.put(CITYNAME, cityname);cv.put(CITYID, cityid);cv.put(PROVINCEID, cityid);cv.put(SORT_KEY, sortKey);cv.put(PROVINCENAME, String.valueOf(provincenameHashMap.get(provinceid)));list.add(cv);}if (list.size() > 0) {setAdapter(list);}}

setAdapter函数

private void setAdapter(List<ContentValues> list) {adapter = new ListAdapter(this, list);cityListView.setAdapter(adapter);}

相应的adapter类

private class ListAdapter extends BaseAdapter implements SectionIndexer {private LayoutInflater inflater;private List<ContentValues> list;private HashMap<String, Integer> alphaIndexer;private String[] sections;public ListAdapter(Context context, List<ContentValues> list) {this.inflater = LayoutInflater.from(context);this.list = list;this.alphaIndexer = new HashMap<String, Integer>();this.sections = new String[list.size()];for (int i = 0; i < list.size(); i++) {String name = getPinyin(list.get(i).getAsString(SORT_KEY));alphaIndexer.put(name, i);sections[i] = name;}}@Overridepublic int getCount() {return list.size();}@Overridepublic Object getItem(int position) {return list.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder;if (convertView == null) {convertView = inflater.inflate(R.layout.list_item, null);holder = new ViewHolder();holder.alpha = (TextView) convertView.findViewById(R.id.alpha);holder.name = (TextView) convertView.findViewById(R.id.name);holder.provincename=(TextView)convertView.findViewById(R.id.provincename);convertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}ContentValues cv = list.get(position);String name = cv.getAsString(CITYNAME);String provincename=cv.getAsString(PROVINCENAME);holder.name.setText(name);holder.provincename.setText(provincename);String currentStr = cv.getAsString(SORT_KEY);String previewStr = (position - 1) >= 0 ? list.get(position - 1).getAsString(SORT_KEY) : " ";if (!(previewStr.charAt(0)==currentStr.charAt(0))) {holder.alpha.setVisibility(View.VISIBLE);holder.alpha.setText(String.valueOf(currentStr.charAt(0)));} else {holder.alpha.setVisibility(View.GONE);}return convertView;}private class ViewHolder {TextView alpha;TextView name;TextView provincename;}@Overridepublic int getPositionForSection(int section) {String later = section - 2 >= 0 ? sections[section - 2]: sections[section];return alphaIndexer.get(later);}@Overridepublic int getSectionForPosition(int position) {return 0;}@Overridepublic Object[] getSections() {return sections;}}

获取汉字的拼音通过pinyin4j来实现的,函数是

/**      * 获取汉字串拼音,英文字符不变      *      * @param chinese 汉字串      * @return 汉语拼音      */     public static String getPinyin(String chinese) {             StringBuffer pybf = new StringBuffer();             char[] arr = chinese.toCharArray();             HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();             defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);             defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);             for (int i = 0; i < arr.length; i++) {                     if (arr[i] > 128) {                             try {                                     pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);                             } catch (BadHanyuPinyinOutputFormatCombination e) {                                     e.printStackTrace();                             }                     } else {                             pybf.append(arr[i]);                     }             }             return pybf.toString();     } 

开始的一些变量

private BaseAdapter adapter;private ListView cityListView;HashMap<String, Object> provincenameHashMap=new HashMap<String, Object>();private static final String CITYNAME = "cityname", CITYID = "cityid",PROVINCEID="provinceid",SORT_KEY = "sort_key",PROVINCENAME="provincename";ArrayList<HashMap<String, Object>> arrayList=new ArrayList<HashMap<String,Object>>();

将上面的整理一下,贴出代码来:

package com.qn;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.regex.Pattern;import net.sourceforge.pinyin4j.PinyinHelper;import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;import android.R.string;import android.app.Activity;import android.content.AsyncQueryHandler;import android.content.ContentResolver;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ListView;import android.widget.SectionIndexer;import android.widget.TextView;public class OrderByPinyinActivity extends Activity {private BaseAdapter adapter;private ListView cityListView;HashMap<String, Object> provincenameHashMap=new HashMap<String, Object>();private static final String CITYNAME = "cityname", CITYID = "cityid",PROVINCEID="provinceid",SORT_KEY = "sort_key",PROVINCENAME="provincename";ArrayList<HashMap<String, Object>> arrayList=new ArrayList<HashMap<String,Object>>();@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);cityListView = (ListView) findViewById(R.id.listView);bindData();}Comparator<HashMap<String, Object>> comparator = new Comparator<HashMap<String, Object>>() {public int compare(HashMap<String, Object> s1,HashMap<String, Object> s2) {String str1 = s1.get(SORT_KEY).toString();String str2 = s2.get(SORT_KEY).toString();if (str1.compareTo(str2)>0){return 1;}else {return -1;}}};/* * 绑定城市信息,此处为假数据 */public void getcityData(){HashMap<String, Object> hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID, "1");hashcityMap.put(CITYNAME, "青岛");hashcityMap.put(PROVINCEID, "0");//hashcityMap.put(SORT_KEY, getPinyin("青岛"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID,"2");hashcityMap.put(CITYNAME, "济南");hashcityMap.put(PROVINCEID, "0");//hashcityMap.put(SORT_KEY, getPinyin("济南"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID, "3");hashcityMap.put(CITYNAME, "日照");hashcityMap.put(PROVINCEID,"0");//hashcityMap.put(SORT_KEY, getPinyin("日照"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID, "4");hashcityMap.put(CITYNAME, "济宁");hashcityMap.put(PROVINCEID, "0");//hashcityMap.put(SORT_KEY, getPinyin("济宁"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);hashcityMap=new HashMap<String, Object>();hashcityMap.put(CITYID, "5");hashcityMap.put(CITYNAME, "武汉");hashcityMap.put(PROVINCEID, "1");//hashcityMap.put(SORT_KEY, getPinyin("济宁"));hashcityMap.put(SORT_KEY, getPinyin(String.valueOf(hashcityMap.get(CITYNAME))));arrayList.add(hashcityMap);Collections.sort(arrayList,comparator);}/* * 绑定provinceid到省,此处为假数据 */public void getprovinceData(){provincenameHashMap.put("0", "山东");provincenameHashMap.put("1", "湖北");}public void bindData(){getcityData();getprovinceData();if (arrayList != null && arrayList.size() > 0) {List<ContentValues> list = new ArrayList<ContentValues>();for (int i = 0; i < arrayList.size(); i++) {HashMap<String, Object> hashMap=new HashMap<String, Object>();hashMap=arrayList.get(i);ContentValues cv = new ContentValues();String cityname = (String)hashMap.get(CITYNAME);Log.e("cityname",cityname);String cityid = (String)hashMap.get(CITYID);String provinceid = (String)hashMap.get(PROVINCEID);String sortKey = (String)hashMap.get(SORT_KEY);cv.put(CITYNAME, cityname);cv.put(CITYID, cityid);cv.put(PROVINCEID, cityid);cv.put(SORT_KEY, sortKey);cv.put(PROVINCENAME, String.valueOf(provincenameHashMap.get(provinceid)));list.add(cv);}if (list.size() > 0) {setAdapter(list);}}}private void setAdapter(List<ContentValues> list) {adapter = new ListAdapter(this, list);cityListView.setAdapter(adapter);}private class ListAdapter extends BaseAdapter implements SectionIndexer {private LayoutInflater inflater;private List<ContentValues> list;private HashMap<String, Integer> alphaIndexer;private String[] sections;public ListAdapter(Context context, List<ContentValues> list) {this.inflater = LayoutInflater.from(context);this.list = list;this.alphaIndexer = new HashMap<String, Integer>();this.sections = new String[list.size()];for (int i = 0; i < list.size(); i++) {String name = getPinyin(list.get(i).getAsString(SORT_KEY));alphaIndexer.put(name, i);sections[i] = name;}}@Overridepublic int getCount() {return list.size();}@Overridepublic Object getItem(int position) {return list.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder;if (convertView == null) {convertView = inflater.inflate(R.layout.list_item, null);holder = new ViewHolder();holder.alpha = (TextView) convertView.findViewById(R.id.alpha);holder.name = (TextView) convertView.findViewById(R.id.name);holder.provincename=(TextView)convertView.findViewById(R.id.provincename);convertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}ContentValues cv = list.get(position);String name = cv.getAsString(CITYNAME);String provincename=cv.getAsString(PROVINCENAME);holder.name.setText(name);holder.provincename.setText(provincename);String currentStr = cv.getAsString(SORT_KEY);String previewStr = (position - 1) >= 0 ? list.get(position - 1).getAsString(SORT_KEY) : " ";if (!(previewStr.charAt(0)==currentStr.charAt(0))) {holder.alpha.setVisibility(View.VISIBLE);holder.alpha.setText(String.valueOf(currentStr.charAt(0)));} else {holder.alpha.setVisibility(View.GONE);}return convertView;}private class ViewHolder {TextView alpha;TextView name;TextView provincename;}@Overridepublic int getPositionForSection(int section) {String later = section - 2 >= 0 ? sections[section - 2]: sections[section];return alphaIndexer.get(later);}@Overridepublic int getSectionForPosition(int position) {return 0;}@Overridepublic Object[] getSections() {return sections;}}/**      * 获取汉字串拼音,英文字符不变      *      * @param chinese 汉字串      * @return 汉语拼音      */     public static String getPinyin(String chinese) {             StringBuffer pybf = new StringBuffer();             char[] arr = chinese.toCharArray();             HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();             defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);             defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);             for (int i = 0; i < arr.length; i++) {                     if (arr[i] > 128) {                             try {                                     pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);                             } catch (BadHanyuPinyinOutputFormatCombination e) {                                     e.printStackTrace();                             }                     } else {                             pybf.append(arr[i]);                     }             }             return pybf.toString();     } //private String getPinyin(String str) {//return "zzz";//}}

listitem.xml 

<?xml version="1.0" encoding="UTF-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">     <TextView      android:id="@+id/alpha"      android:layout_width="fill_parent"      android:layout_height="wrap_content"      android:paddingLeft="10dip"      android:background="#333333"      android:textColor="#FFFFFF"      android:visibility="gone"      />    <View          android:id="@+id/divider"          android:layout_width="1.0dip"          android:layout_height="fill_parent"          android:layout_marginRight="11.0dip"          android:layout_below="@id/alpha"          android:layout_marginLeft="10dip"        />     <TextView          android:id="@+id/name"          android:textAppearance="?android:textAppearanceMedium"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_marginLeft="2.0dip"          android:layout_marginTop="6.0dip"          android:layout_marginRight="5.0dip"          android:singleLine="true"          android:layout_toRightOf="@id/divider"          android:layout_alignTop="@id/divider"          android:text="城市"        />           <TextView          android:id="@+id/provincename"           android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_marginLeft="5.0dip"          android:layout_marginTop="12.0dip"          android:layout_marginRight="5.0dip"          android:singleLine="true"          android:layout_toRightOf="@+id/name"          android:layout_alignTop="@+id/divider"          android:text="省城"        />  </RelativeLayout>  

主函数main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><ListView android:id="@+id/listView"          android:layout_width="fill_parent"          android:layout_height="fill_parent"          android:fastScrollEnabled="true"          android:focusable="true"          /></LinearLayout>

ok,一个完整的城市列表就有了,哈哈~

原创粉丝点击