按照首字母排序列表常用于手机联系人,或者商品展示
public class PinyinComparator implements Comparator<Product> {
public int compare(Product o1, Product o2) {
if (o1.getLetters().equals("@")
|| o2.getLetters().equals("#")) {
return -1;
} else if (o1.getLetters().equals("#")
|| o2.getLetters().equals("@")) {
return 1;
} else {
return o1.getLetters().compareTo(o2.getLetters());
}
}
}
/**
* 为RecyclerView填充数据
*
* @param date
* @return
*/
fun filledData(date: List<Product>): List<Product> {
val mSortList = ArrayList<Product>()
for (i in date.indices) {
val sortModel = date[i]
//汉字转换成拼音
val pinyin = PinyinUtils.getPingYin(date[i].proName)
val sortString = pinyin.substring(0, 1).toUpperCase()
// 正则表达式,判断首字母是否是英文字母
if (sortString.matches("[A-Z]".toRegex())) {
sortModel.letters = sortString.toUpperCase()
} else {
sortModel.letters = "#"
}
mSortList.add(sortModel)
}
return mSortList
}
Collections.sort(sourceDateList, pinyinComparator)
productAdapter.setNewData(sourceDateList)
public class PinyinUtils {
/**
* 获取拼音
*
* @param inputString
* @return
*/
public static String getPingYin(String inputString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] input = inputString.trim().toCharArray();
String output = "";
try {
for (char curChar : input) {
if (Character.toString(curChar).matches("[\\u4E00-\\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(curChar, format);
output += temp[0];
} else
output += Character.toString(curChar);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return output;
}
/**
* 获取第一个字的拼音首字母
* @param chinese
* @return
*/
public static String getFirstSpell(String chinese) {
StringBuffer pinYinBF = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (char curChar : arr) {
if (curChar > 128) {
try {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(curChar, defaultFormat);
if (temp != null) {
pinYinBF.append(temp[0].charAt(0));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pinYinBF.append(curChar);
}
}
return pinYinBF.toString().replaceAll("\\W", "").trim();
}
}
/**
* 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
*/
@SuppressLint("DefaultLocale")
fun getPositionForSection(section: Int): Int {
for (i in 0 until itemCount) {
val sortStr = mData[i].letters
val firstChar = sortStr.toUpperCase()[0]
if (firstChar.toInt() == section) {
return i
}
}
return -1
}