需要在libs中导入pinyin4j.jar包
Activity布局:
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
android:id="@+id/side_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:paddingRight="10dp"
android:textColor="@color/colorAccent"
android:textSize="15sp" />
------------------------------------------------
MainActivity
package com.example.e.chengshiliebiao;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.Collections;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
public class MainActivity extends AppCompatActivity {
private StickyListHeadersListView listView;
private SideBar sideBar;
private ArrayList list;
private EditText chaxun;
private Button tianjia;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chaxun = (EditText) findViewById(R.id.shousuo);
tianjia = (Button) findViewById(R.id.tianjia);
initView();
initData();
String sousuo = chaxun.getText().toString();
tianjia.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TianJiaActivity.class);
startActivity(intent);
}
});
}
private void initView() {
listView = (StickyListHeadersListView) findViewById(R.id.list);
sideBar = (SideBar) findViewById(R.id.side_bar);
sideBar.setOnStrSelectCallBack(new SideBar.ISideBarSelectCallBack() {
@Override
public void onSelectStr(int index, String selectStr) {
for (int i = 0; i < list.size(); i++) {
if (selectStr.equalsIgnoreCase(list.get(i).getFirstLetter())) {
listView.setSelection(i); // 选择到首字母出现的位置
return;
}
}
}
});
}
private void initData() {
list = new ArrayList<>();
list.add(new User("亳州")); // 亳[bó]属于不常见的二级汉字
list.add(new User("蚌埠"));
list.add(new User("合肥"));
list.add(new User("北京"));
list.add(new User("天津"));
list.add(new User("苏州"));
list.add(new User("宿州"));
list.add(new User("淮北"));
list.add(new User("淮南"));
list.add(new User("黄山"));
list.add(new User("阜阳"));
list.add(new User("滁州"));
list.add(new User("马鞍山"));
list.add(new User("芜湖"));
list.add(new User("铜陵"));
list.add(new User("安庆"));
list.add(new User("六安"));
list.add(new User("池州"));
list.add(new User("巢湖"));
list.add(new User("宣城"));
list.add(new User("福州"));
list.add(new User("南平"));
list.add(new User("界首"));
list.add(new User("明光"));
list.add(new User("天长"));
list.add(new User("桐城"));
list.add(new User("宁国"));
list.add(new User("厦门"));
list.add(new User("三明"));
list.add(new User("莆田"));
list.add(new User("泉州"));
list.add(new User("怀远"));
list.add(new User("漳州"));
list.add(new User("龙岩"));
list.add(new User("兰州"));
list.add(new User("贵阳"));
list.add(new User("石家庄"));
list.add(new User("12345"));
list.add(new User("54321"));
list.add(new User("哈尔滨"));
list.add(new User("郑州"));
list.add(new User("武汉"));
list.add(new User("长沙"));
list.add(new User("长春"));
list.add(new User("南京"));
list.add(new User("南昌"));
list.add(new User("沈阳"));
list.add(new User("大连"));
Collections.sort(list); // 对list进行排序,需要让User实现Comparable接口重写compareTo方法
SortAdapter adapter = new SortAdapter(this, list);
listView.setAdapter(adapter);
}
}
------------------------------------------------------
package com.example.e.chengshiliebiao;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
/**
* ListView适配
* 提供一个方法来获得 保存首字母和该首字母城市的第一个出现的位置HashMap
* 通过记录前一个首字母与当前首字母是否相同,如果不同加入HashMap中同时显示该字母
* @author acer
*
*/
public class SortAdapter extends BaseAdapter implements StickyListHeadersAdapter {
private List list = null;
private Context mContext;
public SortAdapter(Context mContext, List list) {
this.mContext = mContext;
this.list = list;
}
public int getCount() {
return this.list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup arg2) {
ViewHolder viewHolder;
final User user = list.get(position);
if (view == null) {
viewHolder = new ViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.item_city, null);
viewHolder.name = (TextView) view.findViewById(R.id.name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
//根据position获取首字母作为目录catalog
String catalog = list.get(position).getFirstLetter();
viewHolder.name.setText(this.list.get(position).getName());
return view;
}
@Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView==null){
convertView=View.inflate(mContext,R.layout.item,null);
holder=new Holder();
holder.title= (TextView) convertView.findViewById(R.id.catalog_sort);
convertView.setTag(holder);
}else{
holder= (Holder) convertView.getTag();
}
holder.title.setText(PinYinUtils.getFirstLetter(list.get(position).getName()));
return convertView;
}
@Override
public long getHeaderId(int position) {
return PinYinUtils.getFirstLetter(list.get(position).getName()).charAt(0);
}
final static class ViewHolder {
TextView name;
}
class Holder{
TextView title;
}
}
2.顶端字母布局:
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical" >
android:id="@+id/catalog_sort"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E0E0E0"
android:textColor="#454545"
android:textSize="20sp"
android:padding="10dp"/>
3.城市名布局
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical" >
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textColor="#336598"
android:textSize="16sp"
android:padding="10dp"/>
------------------------------------------------------
PinYinUtils
package com.example.e.chengshiliebiao;
import android.text.TextUtils;
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.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
* Created by e on 2017/6/24.
*/
public class PinYinUtils {
/**
* 返回首字母,大写
* @param str
* @return
*/
public static String getFirstLetter(String str) {
if (TextUtils.isEmpty(str)) {
return "";
}
// 得到一个字符串的拼音的大写
String pinyinStr = getPinyin(str).toUpperCase();
// 取拼音字符串的第一个字母
// String first = pinyinStr.substring(0, 1).toLowerCase();
// if (first.matches("[a-z]")) {
//
// } else {
//
// }
char firstCahr = pinyinStr.charAt(0);
// 不是A-Z字母
if (firstCahr > 90 || firstCahr < 65) {
return "#";
}else{ // 代表是A-Z
return String.valueOf(firstCahr);
}
}
/**
* 得到一个字符串的拼音读音
*
* @param chineseStr
* @return
*/
public static String getPinyin(String chineseStr) {
StringBuffer sb = new StringBuffer();
// 将汉字拆分成一个个的char
char[] chars = chineseStr.toCharArray();
// 遍历汉字的每一个char
for (int i = 0; i < chars.length; i++) {
try {
// 汉字的所有读音放在一个pinyins数组
String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(chars[i], getDefaultFormat());
if (pinyins == null) {
sb.append(chars[i]);
} else {
sb.append(pinyins[0]);
}
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
}
return sb.toString();
}
/**
* 设置默认的输出格式
*
* @return
*/
public static HanyuPinyinOutputFormat getDefaultFormat() {
HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
// 去除声调
outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
// 小写
outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
// 包含Unicode特殊字符
outputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
return outputFormat;
}
}
-------------------------------------------------------------------------
SideBar
package com.example.e.chengshiliebiao;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;
/**
* Created by e on 2017/6/23.
*/
public class SideBar extends TextView {
private String[] letters = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z", "#"};
private Paint textPaint;
private Paint bigTextPaint;
private Paint scaleTextPaint;
private Canvas canvas;
private int itemH;
private int w;
private int h;
/**
* 普通情况下字体大小
*/
float singleTextH;
/**
* 缩放离原始的宽度
*/
private float scaleWidth;
/**
* 滑动的Y
*/
private float eventY = 0;
/**
* 缩放的倍数
*/
private int scaleSize = 1;
/**
* 缩放个数item,即开口大小
*/
private int scaleItemCount = 6;
private ISideBarSelectCallBack callBack;
public SideBar(Context context) {
this(context, null);
}
public SideBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SideBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.SideBar);
scaleSize = ta.getInteger(R.styleable.SideBar_scaleSize, 1);
scaleItemCount = ta.getInteger(R.styleable.SideBar_scaleItemCount, 6);
scaleWidth = ta.getDimensionPixelSize(R.styleable.SideBar_scaleWidth, dp(100));
ta.recycle();
}
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(getCurrentTextColor());
textPaint.setTextSize(getTextSize());
textPaint.setTextAlign(Paint.Align.CENTER);
bigTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bigTextPaint.setColor(getCurrentTextColor());
bigTextPaint.setTextSize(getTextSize() * (scaleSize + 3));
bigTextPaint.setTextAlign(Paint.Align.CENTER);
scaleTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
scaleTextPaint.setColor(getCurrentTextColor());
scaleTextPaint.setTextSize(getTextSize() * (scaleSize + 1));
scaleTextPaint.setTextAlign(Paint.Align.CENTER);
}
public void setDataResource(String[] data) {
letters = data;
invalidate();
}
public void setOnStrSelectCallBack(ISideBarSelectCallBack callBack) {
this.callBack = callBack;
}
/**
* 设置字体缩放比例
*
* @param scale
*/
public void setScaleSize(int scale) {
scaleSize = scale;
invalidate();
}
/**
* 设置缩放字体的个数,即开口大小
*
* @param scaleItemCount
*/
public void setScaleItemCount(int scaleItemCount) {
this.scaleItemCount = scaleItemCount;
invalidate();
}
private int dp(int px) {
final float scale = getContext().getResources().getDisplayMetrics().density;
return (int) (px * scale + 0.5f);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
if (event.getX() > (w - getPaddingRight() - singleTextH - 10)) {
eventY = event.getY();
invalidate();
return true;
} else {
eventY = 0;
invalidate();
break;
}
case MotionEvent.ACTION_CANCEL:
eventY = 0;
invalidate();
return true;
case MotionEvent.ACTION_UP:
if (event.getX() > (w - getPaddingRight() - singleTextH - 10)) {
eventY = 0;
invalidate();
return true;
} else
break;
}
return super.onTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
this.canvas = canvas;
DrawView(eventY);
}
private void DrawView(float y) {
int currentSelectIndex = -1;
if (y != 0) {
for (int i = 0; i < letters.length; i++) {
float currentItemY = itemH * i;
float nextItemY = itemH * (i + 1);
if (y >= currentItemY && y < nextItemY) {
currentSelectIndex = i;
if (callBack != null) {
callBack.onSelectStr(currentSelectIndex, letters[i]);
}
//画大的字母
Paint.FontMetrics fontMetrics = bigTextPaint.getFontMetrics();
float bigTextSize = fontMetrics.descent - fontMetrics.ascent;
canvas.drawText(letters[i], w - getPaddingRight() - scaleWidth - bigTextSize, singleTextH + itemH * i, bigTextPaint);
}
}
}
drawLetters(y, currentSelectIndex);
}
private void drawLetters(float y, int index) {
//第一次进来没有缩放情况,默认画原图
if (index == -1) {
w = getMeasuredWidth();
h = getMeasuredHeight();
itemH = h / letters.length;
Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
singleTextH = fontMetrics.descent - fontMetrics.ascent;
for (int i = 0; i < letters.length; i++) {
canvas.drawText(letters[i], w - getPaddingRight(), singleTextH + itemH * i, textPaint);
}
//触摸的时候画缩放图
} else {
//遍历所有字母
for (int i = 0; i < letters.length; i++) {
//要画的字母的起始Y坐标
float currentItemToDrawY = singleTextH + itemH * i;
float centerItemToDrawY;
if (index < i)
centerItemToDrawY = singleTextH + itemH * (index + scaleItemCount);
else
centerItemToDrawY = singleTextH + itemH * (index - scaleItemCount);
float delta = 1 - Math.abs((y - currentItemToDrawY) / (centerItemToDrawY - currentItemToDrawY));
float maxRightX = w - getPaddingRight();
//如果大于0,表明在y坐标上方
scaleTextPaint.setTextSize(getTextSize() + getTextSize() * delta);
float drawX = maxRightX - scaleWidth * delta;
//超出边界直接花在边界上
if (drawX > maxRightX)
canvas.drawText(letters[i], maxRightX, singleTextH + itemH * i, textPaint);
else
canvas.drawText(letters[i], drawX, singleTextH + itemH * i, scaleTextPaint);
}
}
}
public interface ISideBarSelectCallBack {
void onSelectStr(int index, String selectStr);
}
}
----------------------------------------------------------------
User
package com.example.e.chengshiliebiao;
/**
* Created by e on 2017/6/23.
*/
public class User implements Comparable {
private String name; // 姓名
private String pinyin; // 姓名对应的拼音
private String firstLetter; // 拼音的首字母
public User() {
}
public User(String name) {
this.name = name;
pinyin = PinYinUtils.getPinyin(name); // 根据姓名获取拼音
firstLetter = pinyin.substring(0, 1).toUpperCase(); // 获取拼音首字母并转成大写
if (!firstLetter.matches("[A-Z]")) { // 如果不在A-Z中则默认为“#”
firstLetter = "#";
}
}
public String getName() {
return name;
}
public String getPinyin() {
return pinyin;
}
public String getFirstLetter() {
return firstLetter;
}
@Override
public int compareTo(User another) {
if (firstLetter.equals("#") && !another.getFirstLetter().equals("#")) {
return 1;
} else if (!firstLetter.equals("#") && another.getFirstLetter().equals("#")){
return -1;
} else {
return pinyin.compareToIgnoreCase(another.getPinyin());
}
}
}