最近按照公司需要,写了一个按照城市首字母排序的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;
}
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public 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;
}
@Override
public int getPositionForSection(int section) {
String later = section - 2 >= 0 ? sections[section - 2] : sections[section];
return alphaIndexer.get(later);
}
@Override
public int getSectionForPosition(int position) {
return 0;
}
@Override
public 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>>();
@Override
public 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;
}
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public 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;
}
@Override
public int getPositionForSection(int section) {
String later = section - 2 >= 0 ? sections[section - 2] : sections[section];
return alphaIndexer.get(later);
}
@Override
public int getSectionForPosition(int position) {
return 0;
}
@Override
public 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,一个完整的城市列表就有了,哈哈~
转载请注明:http://www.wandouhome.com/?p=10144
获得城市信息,此处为假数据,大家可以自行添加自己的服务器端数据:
/*
* 绑定城市信息,此处为假数据
*/
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;
}
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public 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;
}
@Override
public int getPositionForSection(int section) {
String later = section - 2 >= 0 ? sections[section - 2] : sections[section];
return alphaIndexer.get(later);
}
@Override
public int getSectionForPosition(int position) {
return 0;
}
@Override
public 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>>();
@Override
public 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;
}
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public 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;
}
@Override
public int getPositionForSection(int section) {
String later = section - 2 >= 0 ? sections[section - 2] : sections[section];
return alphaIndexer.get(later);
}
@Override
public int getSectionForPosition(int position) {
return 0;
}
@Override
public 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,一个完整的城市列表就有了,哈哈~
转载请注明:http://www.wandouhome.com/?p=10144
相关推荐
这个"Android选择城市Demo"提供了一种实现方式,允许用户通过输入城市拼音或首字母进行快速搜索。以下是关于这个Demo的一些关键知识点: 1. **ListView与Adapter**: 选择城市界面通常会使用ListView来展示城市列表...
其次,**拼音检索**在中国市场尤为关键,因为许多中国用户习惯于通过输入城市拼音首字母来搜索。为了实现这一功能,开发者需要处理中文字符到拼音的转换。可以使用开源库如Pinyin4j或Google的libphonenumber来完成此...
- 搜索功能:对于按拼音排列的JSON,可以创建一个查找函数,根据输入的拼音首字母快速定位到对应的城市。 - 层级选择:对于按省市区排列的JSON,可以实现多级联动选择,用户先选择省份,再选择城市,最后选择区县...
在开发一款仿团购应用的过程中,实现一个按照首字母分类的城市选择列表是至关重要的功能,它为用户提供方便快捷的检索方式,提升用户体验。本篇将详细阐述如何构建这样一个功能,主要涉及的技术点包括Android开发、...
为了实现字母排序,我们需要对城市名称进行预处理,按照汉语拼音的首字母进行排序。 1. **数据结构与排序**: - 数据存储:城市数据通常存储在数据库(如SQLite)或JSON文件中,每个城市包含名称等属性。我们需要...
其次,为了实现按拼音首字母分类的功能,需要对城市数据进行预处理,按照拼音的首字母进行分组。这通常通过Java或Kotlin的Map来实现,键是拼音首字母,值是一个包含对应首字母城市列表的ArrayList。这样,用户可以...
使用Collections.sort()方法对城市列表按照拼音首字母排序。接下来,创建一个自定义的Adapter,继承自ArrayAdapter或RecyclerView.Adapter,重写getViewTypeCount()和getItemViewType()方法,以区分城市列表项和字母...
这可以通过比较ListView当前位置和每个城市拼音首字母来实现。如果当前位置的首字母与导航栏的某个字母匹配,就将该字母设为高亮状态。 在CityListDemo项目中,开发者可能已经实现了上述所有功能。这个项目可能包含...
开发者需要自定义AlphabetIndexer,将城市首字母映射到相应的数据位置。 3. FastAdapter(或RecyclerView): - **FastAdapter**是一个强大的开源库,它扩展了Android的RecyclerView,提供了更高效的列表视图操作...
此外,对于拼音搜索,还可以考虑拼音首字母索引,比如A-Z的侧滑菜单,让用户能快速定位到某一拼音范围的城市。 在实际开发中,还要考虑用户体验的细节。例如,设计清晰的UI界面,合理布局,以及良好的错误处理机制...
- 字母排序是按照城市名称的首字母进行排列,便于用户按照字母顺序浏览。在Android中,这通常通过对城市名转换为拼音并进行比较来实现。 2. **pinyin4j库**: - pinyin4j是一个Java库,用于处理汉字到拼音的转换...
通过将城市名转换为拼音,然后根据拼音首字母进行排序,实现了A-Z的字母索引效果。用户可以通过滑动或点击字母导航栏快速跳转到对应字母开头的城市列表部分。 此外,触摸查找功能也是此项目的一个重要特性。这可能...
“字母联动城市列表”是指城市列表按照拼音首字母排序,并且可以在界面上展示一个字母索引条,用户点击某个字母可以快速跳转到该字母开头的城市列表。这样的设计大大提升了查找效率,尤其在处理大量城市数据时。 ...
这样,用户可以根据拼音首字母快速滚动或搜索城市,提高用户体验。 3. **百度地图API集成**: - 百度地图SDK提供了丰富的地图、定位、搜索等功能。在这个Demo中,可能使用了地图API来展示城市的位置,以及提供地理...
在Ionic城市列表中,锚点定位可能用于各个城市分类或首字母索引,让用户能快速找到目标城市,提升用户体验。 **四、 搜索功能** 搜索功能在城市列表中必不可少,它允许用户输入关键字快速查找所需城市。在Ionic中,...
3. **数据结构**:城市数据可以使用`HashMap`存储,键为拼音首字母,值为包含该首字母所有城市的列表。这样在查找和排序时能保持较高的效率。 4. **热门和定位**:在数据加载时,判断每个城市是否为热门或用户当前...
2. **拼音首字母搜索**:为了提高用户体验,城市选择器会提供按拼音首字母快速筛选的功能。实现这一功能,我们需要先对城市列表进行预处理,生成每个城市名称的首字母索引。在JavaScript中,可以使用`pinyin`库来...
本项目旨在实现一个功能完善的Android城市列表,该列表按照字母顺序排列,并且右侧带有字母索引,点击字母可快速跳转至相应字母开头的城市。以下是关于这个功能的详细实现步骤和涉及的关键知识点。 首先,我们需要...
例如,对于中文,我们可以转换为拼音并获取首字母,或者根据Unicode值进行排序。 9. **性能优化**: 为了提高性能,可以考虑使用SparseArray存储已计算好的索引,避免每次滑动都重新计算。此外,对于大量数据,...