在手机中,尤其是联系人列表界面或者应用的搜索列表界面,我们会看到一种类似于下述效果的界面,随着侧边栏的滑动,列表显示在指定字母处。该控件是如何实现的呢?这还是之前研究环信的demo时记录的一个例子,该控件的实现来自环信demo。
代码:
侧边栏EaseSideBar.java:
public class EaseSidebar extends View{
private Paint paint;
private TextView header;
private float height;
private ListView mListView;
private Context context;
private SectionIndexer sectionIndexter = null;
public void setListView(ListView listView){
mListView = listView;
}
public EaseSidebar(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
private String[] sections;
private void init(){
String st = context.getString(R.string.search_new);
sections= new String[]{st,"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","#"};
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.parseColor("#8C8C8C"));
paint.setTextAlign(Align.CENTER);
paint.setTextSize(20);
setBackgroundColor(Color.TRANSPARENT); //默认透明,避免遮盖ListView的右侧部分
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float center = getWidth() / 2;
height = getHeight() / sections.length;
for (int i = sections.length - 1; i > -1; i--) {
canvas.drawText(sections[i], center, height * (i+1), paint);
}
}
private int sectionForPoint(float y) {
int index = (int) (y / height);
if(index < 0) {
index = 0;
}
if(index > sections.length - 1){
index = sections.length - 1;
}
return index;
}
private void setHeaderTextAndscroll(MotionEvent event){
if (mListView == null) {
//check the mListView to avoid NPE. but the mListView shouldn‘t be null
//need to check the call stack later
return;
}
String headerString = sections[sectionForPoint(event.getY())];
header.setText(headerString);
ListAdapter adapter = mListView.getAdapter();
if(sectionIndexter == null){
if(adapter instanceof HeaderViewListAdapter){
sectionIndexter = (SectionIndexer) ((HeaderViewListAdapter) adapter).getWrappedAdapter();
}else if(adapter instanceof SectionIndexer){
sectionIndexter = (SectionIndexer)adapter;
}else{
throw new RuntimeException("listview sets adpater does not implement SectionIndexer interface");
}
}
String[] adapterSections = (String[]) sectionIndexter.getSections();
try {
for (int i = adapterSections.length - 1; i > -1; i--) {
if(adapterSections[i].equals(headerString)){
Log.i("EaseSidebar", " equals setSelection() " + headerString);
mListView.setSelection(sectionIndexter.getPositionForSection(i));
break;
}
}
} catch (Exception e) {
Log.e("EaseSidebar", e.getMessage());
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:{
if(header == null){
header = (TextView) ((View)getParent()).findViewById(R.id.floating_header);
}
setHeaderTextAndscroll(event);
header.setVisibility(View.VISIBLE);
setBackgroundResource(R.drawable.ease_sidebar_background_pressed);
return true;
}
case MotionEvent.ACTION_MOVE:{
setHeaderTextAndscroll(event);
return true;
}
case MotionEvent.ACTION_UP:
header.setVisibility(View.INVISIBLE);
setBackgroundColor(Color.TRANSPARENT);
return true;
case MotionEvent.ACTION_CANCEL:
header.setVisibility(View.INVISIBLE);
setBackgroundColor(Color.TRANSPARENT);
return true;
}
return super.onTouchEvent(event);
}
}
主界面布局:activity_communicate_first.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg_default"
tools:context=".CommunicateFirstActivity" >
<TextView
android:id="@+id/title_bar"
android:layout_width="match_parent"
android:layout_height="@dimen/height_top_bar"
android:background="@color/top_bar_normal_bg"
android:gravity="center_vertical"
android:text="@string/commDes"
android:textSize="26sp" />
<include
android:id="@+id/search_layout"
layout="@layout/em_search_bar_with_padding" />
<ListView
android:id="@+id/contact_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/search_layout"
android:scrollbars="none" >
</ListView>
<com.test.communicatehx.EaseSidebar
android:id="@+id/sidebar"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@id/contact_list" >
</com.test.communicatehx.EaseSidebar>
<TextView
android:id="@+id/floating_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/ease_show_head_toast_bg"
android:gravity="center"
android:paddingLeft="25dp"
android:paddingRight="25dp"
android:textColor="@android:color/white"
android:textSize="40sp"
android:visibility="invisible" />
</RelativeLayout>
搜索布局:em_search_bar_with_padding.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="wrap_content"
android:paddingLeft="@dimen/padding_search_bar"
android:paddingRight="27dp"
android:paddingTop="7dp"
android:paddingBottom="7dp"
android:background="#ededed"
android:layout_marginTop="@dimen/height_top_bar"
>
<EditText
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:id="@+id/search_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@drawable/em_seabar_input"
android:drawableLeft="@drawable/em_search_bar_icon_normal"
android:focusable="true"
android:focusableInTouchMode="true"
android:hint="@string/search_bar"
android:textSize="16sp"
android:layout_marginLeft="4dp"
android:singleLine="true"
/>
<ImageButton
android:id="@+id/search_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="3dp"
android:background="@android:color/transparent"
android:padding="6dp"
android:src="@drawable/ease_search_clear"
/>
</RelativeLayout>
主Activity的实现:
1 private void initSearchUI(){
2 searchEdit = (EditText) findViewById(R.id.search_edit);
3 searchClear = (ImageButton) findViewById(R.id.search_clear);
4
5 searchEdit.addTextChangedListener(new TextWatcher() {
6
7 @Override
8 public void onTextChanged(CharSequence s, int start, int before, int count) {
9 // TODO Auto-generated method stub
10 if(contactAdapter != null){
11 contactAdapter.getFilter().filter(s);
12 }
13 if(s.length() > 0){
14 searchClear.setVisibility(View.VISIBLE);
15 }else{
16 searchClear.setVisibility(View.GONE);
17 }
18 }
19
20 @Override
21 public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
22 int arg3) {
23 }
24 @Override
25 public void afterTextChanged(Editable arg0) {
26 }
27 });
28
29 searchClear.setOnClickListener(new OnClickListener() {
30 @Override
31 public void onClick(View arg0) {
32 // TODO Auto-generated method stub
33 searchEdit.getText().clear(); //清空
34 hideSoftKeyboard();
35 }
36 });
37
38 }
39
40 private void hideSoftKeyboard(){ //隐藏软键盘
41 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
42 imm.hideSoftInputFromWindow(searchEdit.getWindowToken(),0);
43 }
44
45 private void testListView(){
46 contactList = (ListView) findViewById(R.id.contact_list); //主搜索列表
47
48 easeSideBar = (EaseSidebar) findViewById(R.id.sidebar); //右侧边栏
49 easeSideBar.setListView(contactList);
50
51 contactAdapter = new ContactAdapter(this); //搜索内容适配器
52 contactList.setAdapter(contactAdapter);
53 }
左侧列表:按照字母分组排序的显示及点击搜索时显示的效果。
1 package com.test.communicatehx;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
6 import java.util.List;
7 import java.util.Locale;
8
9 import com.test.spell.SpellTest;
10 import com.test.testandroid.R;
11
12 import android.content.Context;
13 import android.util.Log;
14 import android.util.SparseIntArray;
15 import android.view.LayoutInflater;
16 import android.view.View;
17 import android.view.ViewGroup;
18 import android.widget.BaseAdapter;
19 import android.widget.Filter;
20 import android.widget.Filterable;
21 import android.widget.SectionIndexer;
22 import android.widget.TextView;
23
24 public class ContactAdapter extends BaseAdapter implements SectionIndexer,Filterable{
25 private Context mContext;
26 private LayoutInflater layoutInflater;
27 // private ContactInfo[] datas;
28 private SparseIntArray positionOfSection;
29 private SparseIntArray sectionOfPosition;
30
31 private List<ContactInfo> contactList;
32
33 //过滤相关
34 private ArrayList<ContactInfo> originalValues;
35 private final Object mLock = new Object();
36
37 public ContactAdapter(Context context) {
38 // TODO Auto-generated constructor stub
39 mContext = context;
40 layoutInflater = LayoutInflater.from(context);
41 contactList = new ArrayList<ContactAdapter.ContactInfo>();
42 String []arr = context.getResources().getStringArray(R.array.arr_list);
43 for (String name : arr) {
44 ContactInfo info = new ContactInfo();
45 info.name = name;
46 info.nameLetter = SpellTest.trans2PinYin(name).toUpperCase(Locale.getDefault()); //转化成拼音---统一为大写字母避免排序出错(因同一个字母大小写,顺序不一样)
47 info.firstLetter = info.nameLetter.substring(0, 1);
48 // Log.d(TAG, "info.firstLetter: "+ info.firstLetter);
49 contactList.add(info);
50 }
51
52 Collections.sort(contactList, COMPARATOR); //按字母排序
53 }
54
55 private Comparator<ContactInfo> COMPARATOR = new Comparator<ContactAdapter.ContactInfo>() {
56 @Override
57 public int compare(ContactInfo o1, ContactInfo o2) {
58 // TODO Auto-generated method stub
59 return o1.nameLetter.compareTo(o2.nameLetter); //默认系统字符比较
60 }
61 };
62
63 @Override
64 public int getCount() {
65 // TODO Auto-generated method stub
66 return contactList.size();
67 }
68
69 @Override
70 public ContactInfo getItem(int position) {
71 // TODO Auto-generated method stub
72 return contactList.get(position);
73 }
74
75 @Override
76 public long getItemId(int position) {
77 // TODO Auto-generated method stub
78 return position;
79 }
80
81 @Override
82 public View getView(int position, View convertView, ViewGroup parent) {
83 // TODO Auto-generated method stub
84 ContactHolder ch;
85 if(convertView == null){
86 convertView = layoutInflater.inflate(R.layout.contact_view, null);
87 ch = new ContactHolder();
88 ch.nameText = (TextView) convertView.findViewById(R.id.contact_name);
89 ch.groupText = (TextView) convertView.findViewById(R.id.group_title);
90 convertView.setTag(ch);
91 }else{
92 ch = (ContactHolder) convertView.getTag();
93 }
94
95 ContactInfo info = contactList.get(position);
96 if(info != null){
97 ch.nameText.setText(info.name);
98
99 if(position ==0 || !isItentical(position)){
100 ch.groupText.setText(info.firstLetter);
101 ch.groupText.setVisibility(View.VISIBLE);
102 }else{
103 ch.groupText.setVisibility(View.GONE);
104 }
105 }
106
107 return convertView;
108 }
109
110 private boolean isItentical(int position){
111 String s1 = contactList.get(position).firstLetter;
112 String s2 = contactList.get(position-1).firstLetter;
113
114 // Log.i(TAG, "s1: " + s1 + " s2: " + s2);
115
116 if(s1 == null || s2 == null){
117 return false;
118 }
119 return s1.equals(s2);
120 }
121
122 //重写sectionIndexer相关方法
123 /**
124 * 根据分类列的索引号获得该序列的首个位置
125 */
126 @Override
127 public int getPositionForSection(int section) {
128 // TODO Auto-generated method stub
129 Log.i(TAG, "getPositionForSection() section: " + section);
130 return positionOfSection.get(section);
131 }
132
133 /**
134 * 通过该项的位置,获得所在分类组的索引号
135 */
136 @Override
137 public int getSectionForPosition(int position) {
138 // TODO Auto-generated method stub
139 Log.i(TAG, "getSectionForPosition() position: " + position);
140 return sectionOfPosition.get(position);
141 }
142
143 private List<String> tmpList = new ArrayList<String>();
144 @Override
145 public Object[] getSections() {
146 // TODO Auto-generated method stub
147
148 positionOfSection = new SparseIntArray();
149 sectionOfPosition = new SparseIntArray();
150 int count = getCount();
151 tmpList.clear(); //重置
152 tmpList.add(mContext.getString(R.string.search_new));
153 positionOfSection.put(0, 0);
154 sectionOfPosition.put(0, 0);
155 for (int i = 1; i < count; i++) {
156 String letter = getItem(i).firstLetter; //子项标题首字母
157 int section = tmpList.size() - 1;
158
159 Log.i(TAG, "getSections() section: " + section +" firstLetter: " + letter);
160
161 if (tmpList.get(section) != null && !tmpList.get(section).equals(letter)) {
162 tmpList.add(letter);
163 section++;
164 positionOfSection.put(section, i);
165 }
166 sectionOfPosition.put(i, section);
167 }
168
169 return tmpList.toArray(new String[tmpList.size()]);
170
171 }
172
173 private final String TAG = "ContactAdapter";
174 class ContactHolder{
175 TextView nameText;
176 TextView groupText;
177 }
178
179 class ContactInfo{
180 String name; //名称
181 String nameLetter; //名称全拼
182 String firstLetter; //名称首字母 ----作为该组的名称
183 }
184
185 private ContactFilter contactFilter;
186 @Override
187 public Filter getFilter() {
188 // TODO Auto-generated method stub
189 if(contactFilter == null){
190 contactFilter = new ContactFilter();
191 }
192 return contactFilter;
193 }
194
195 class ContactFilter extends Filter{
196
197 @Override
198 protected FilterResults performFiltering(CharSequence prefix) {
199 // TODO Auto-generated method stub
200 // 持有过滤操作完成之后的数据。该数据包括过滤操作之后的数据的值以及数量。 count:数量 values包含过滤操作之后的数据的值
201 FilterResults results = new FilterResults();
202
203 if (originalValues == null) {
204 synchronized (mLock) {
205 // 将list的用户 集合转换给这个原始数据的ArrayList
206 originalValues = new ArrayList<ContactInfo>(contactList);
207 }
208 }
209 if (prefix == null || prefix.length() == 0) {
210 synchronized (mLock) {
211 ArrayList<ContactInfo> list = new ArrayList<ContactInfo>(
212 originalValues);
213 results.values = list;
214 results.count = list.size();
215 }
216 } else {
217 // 做正式的筛选 ---当前按照文本搜索,具体情况具体分析,有的可能按照拼音首字母
218 // 声明一个临时的集合对象 将原始数据赋给这个临时变量
219 final ArrayList<ContactInfo> values = originalValues;
220
221 // 新的集合对象
222 final ArrayList<ContactInfo> newValues = new ArrayList<ContactInfo>();
223
224 for (ContactInfo contactInfo : values) {
225 if(contactInfo.name.contains(prefix)){
226 newValues.add(contactInfo);
227 }
228 }
229
230 // 然后将这个新的集合数据赋给FilterResults对象
231 results.values = newValues;
232 results.count = newValues.size();
233 }
234
235 return results;
236 }
237
238 @Override
239 protected void publishResults(CharSequence constraint, FilterResults results) {
240 // TODO Auto-generated method stub
241 // 重新将与适配器相关联的List重赋值一下
242 contactList.clear();
243 contactList = (List<ContactInfo>) results.values;
244
245 if (results.count > 0) {
246 notifyDataSetChanged();
247 } else {
248 notifyDataSetInvalidated();
249 }
250
251 }
252 }
253
254 }
关于将汉字转化为拼音的使用的是一个工具类,但是由于时间久远,遗漏了原文链接,我也在网上查找对比了一下,可能的链接:https://www.jb51.net/article/116091.htm 若有什么问题,可留言告知,谢谢!
1 package com.test.spell;
2
3 public class SpellTest {
4
5 private static int[] pyvalue = new int[] { -20319, -20317, -20304, -20295,
6 -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036,
7 -20032, -20026, -20002, -19990, -19986, -19982, -19976, -19805,
8 -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741,
9 -19739, -19728, -19725, -19715, -19540, -19531, -19525, -19515,
10 -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275,
11 -19270, -19263, -19261, -19249, -19243, -19242, -19238, -19235,
12 -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006,
13 -19003, -18996, -18977, -18961, -18952, -18783, -18774, -18773,
14 -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697,
15 -18696, -18526, -18518, -18501, -18490, -18478, -18463, -18448,
16 -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201,
17 -18184, -18183, -18181, -18012, -17997, -17988, -17970, -17964,
18 -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752,
19 -17733, -17730, -17721, -17703, -17701, -17697, -17692, -17683,
20 -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427,
21 -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,
22 -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470,
23 -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423,
24 -16419, -16412, -16407, -16403, -16401, -16393, -16220, -16216,
25 -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158,
26 -16155, -15959, -15958, -15944, -15933, -15920, -15915, -15903,
27 -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659,
28 -15652, -15640, -15631, -15625, -15454, -15448, -15436, -15435,
29 -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369,
30 -15363, -15362, -15183, -15180, -15165, -15158, -15153, -15150,
31 -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121,
32 -15119, -15117, -15110, -15109, -14941, -14937, -14933, -14930,
33 -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902,
34 -14894, -14889, -14882, -14873, -14871, -14857, -14678, -14674,
35 -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429,
36 -14407, -14399, -14384, -14379, -14368, -14355, -14353, -14345,
37 -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135,
38 -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,
39 -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907,
40 -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847,
41 -13831, -13658, -13611, -13601, -13406, -13404, -13400, -13398,
42 -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343,
43 -13340, -13329, -13326, -13318, -13147, -13138, -13120, -13107,
44 -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888,
45 -12875, -12871, -12860, -12858, -12852, -12849, -12838, -12831,
46 -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556,
47 -12359, -12346, -12320, -12300, -12120, -12099, -12089, -12074,
48 -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798,
49 -11781, -11604, -11589, -11536, -11358, -11340, -11339, -11324,
50 -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041,
51 -11038, -11024, -11020, -11019, -11018, -11014, -10838, -10832,
52 -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533,
53 -10519, -10331, -10329, -10328, -10322, -10315, -10309, -10307,
54 -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254 };
55 private static String[] pystr = new String[] { "a", "ai", "an", "ang",
56 "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng",
57 "bi", "bian", "biao", "bie", "bin", "bing", "bo", "bu", "ca",
58 "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan",
59 "chang", "chao", "che", "chen", "cheng", "chi", "chong", "chou",
60 "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci",
61 "cong", "cou", "cu", "cuan", "cui", "cun", "cuo", "da", "dai",
62 "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die",
63 "ding", "diu", "dong", "dou", "du", "duan", "dui", "dun", "duo",
64 "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo",
65 "fou", "fu", "ga", "gai", "gan", "gang", "gao", "ge", "gei", "gen",
66 "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui",
67 "gun", "guo", "ha", "hai", "han", "hang", "hao", "he", "hei",
68 "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang",
69 "hui", "hun", "huo", "ji", "jia", "jian", "jiang", "jiao", "jie",
70 "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka",
71 "kai", "kan", "kang", "kao", "ke", "ken", "keng", "kong", "kou",
72 "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la",
73 "lai", "lan", "lang", "lao", "le", "lei", "leng", "li", "lia",
74 "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long",
75 "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai", "man",
76 "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao",
77 "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai", "nan",
78 "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang",
79 "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan",
80 "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei",
81 "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po",
82 "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing",
83 "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao",
84 "re", "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui",
85 "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen",
86 "seng", "sha", "shai", "shan", "shang", "shao", "she", "shen",
87 "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang",
88 "shui", "shun", "shuo", "si", "song", "sou", "su", "suan", "sui",
89 "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng",
90 "ti", "tian", "tiao", "tie", "ting", "tong", "tou", "tu", "tuan",
91 "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen",
92 "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", "xie",
93 "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya",
94 "yan", "yang", "yao", "ye", "yi", "yin", "ying", "yo", "yong",
95 "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang",
96 "zao", "ze", "zei", "zen", "zeng", "zha", "zhai", "zhan", "zhang",
97 "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu",
98 "zhua", "zhuai", "zhuan", "zhuang", "zhui", "zhun", "zhuo", "zi",
99 "zong", "zou", "zu", "zuan", "zui", "zun", "zuo" };
100 private StringBuilder buffer;
101 private String resource;
102 private static SpellTest chineseSpelling = new SpellTest();
103 public static SpellTest getInstance() {
104 return chineseSpelling;
105 }
106 public String getResource() {
107 return resource;
108 }
109 public void setResource(String resource) {
110 this.resource = resource;
111 }
112 private int getChsAscii(String chs) {
113 int asc = 0;
114 try {
115 byte[] bytes = chs.getBytes("gb2312");
116 if (bytes == null || bytes.length > 2 || bytes.length <= 0) { // 错误
117 // log
118 throw new RuntimeException("illegal resource string");
119 // System.out.println("error");
120 }
121 if (bytes.length == 1) { // 英文字符
122 asc = bytes[0];
123 }
124 if (bytes.length == 2) { // 中文字符
125 int hightByte = 256 + bytes[0];
126 int lowByte = 256 + bytes[1];
127 asc = (256 * hightByte + lowByte) - 256 * 256;
128 }
129 } catch (Exception e) {
130 System.out
131 .println("ERROR:ChineseSpelling.class-getChsAscii(String chs)"
132 + e);
133 // e.printStackTrace();
134 }
135 return asc;
136 }
137 /**
138 * 转换单个汉字
139 *
140 * @param str
141 * @return
142 */
143 public String convert(String str) {
144 String result = null;
145 int ascii = getChsAscii(str);
146 if (ascii > 0 && ascii < 160) {
147 result = String.valueOf((char) ascii);
148 } else {
149 for (int i = (pyvalue.length - 1); i >= 0; i--) {
150 if (pyvalue[i] <= ascii) {
151 result = pystr[i];
152 break;
153 }
154 }
155 }
156 return result;
157 }
158 /**
159 * 转换一个或多个汉字
160 *
161 * @param str
162 * @return
163 */
164 public String convertAll(String str) {
165 String result = "";
166 String strTemp = null;
167 for (int j = 0; j < str.length(); j++) {
168 strTemp = str.substring(j, j + 1);
169 int ascii = getChsAscii(strTemp);
170 if (ascii > 0 && ascii < 160) {
171 result += String.valueOf((char) ascii);
172 } else {
173 for (int i = (pyvalue.length - 1); i >= 0; i--) {
174 if (pyvalue[i] <= ascii) {
175 result += pystr[i];
176 break;
177 }
178 }
179 }
180 }
181 return result;
182 }
183 public String getSelling(String chs) {
184 String key, value;
185 buffer = new StringBuilder();
186 for (int i = 0; i < chs.length(); i++) {
187 key = chs.substring(i, i + 1);
188 if (key.getBytes().length == 2) {
189 value = (String) convert(key);
190 if (value == null) {
191 value = "unknown";
192 }
193 } else {
194 value = key;
195 }
196 buffer.append(value);
197 }
198 return buffer.toString();
199 }
200 private String getSpelling() {
201 return this.getSelling(this.getResource());
202 }
203
204 /**
205 * 转换为拼音
206 * @param str
207 * @return
208 */
209 public static String trans2PinYin(String str) {
210 return SpellTest.getInstance().convertAll(str);
211 }
212
213
214
215 public static void main(String[] args) {
216 String str = "你好,Hello!";
217 //String strPinYin = new Trans2PinYin().convertAll(str);
218 String strPinYin = trans2PinYin(str);
219 System.out.println(strPinYin);
220
221
222 }
223
224
225 }
至此,关于该demo的核心代码已经完成,该文的目的是记录,便于以后查看!
一个搜索侧边栏的工具类EaseSidebar+ListView-A-Z字母分组显示功能demo
原文:https://www.cnblogs.com/sparrowlhl/p/11252021.html