Search Chinese characters using pinyin in android Development
I went back to my house on the National Day. I really didn't want to leave yesterday. It feels so good to be close to home. Alas, don't talk about this. Let's talk about what's going on today.
The previous blog introduced the custom AutoCompleteTextView, but we used a very bad technique, that is, we used the Pinyin of each Chinese character as a field in advance, in actual development, we certainly won't do this. We need to use the code to automatically generate Chinese pinyin characters, just like our mobile phone address book. For example, we need to find the person "Michael, we only need to enter "zs", "cs", "zhangsan", and "changsan" to search for this person. How can we implement this function?
The cases described in this article are implemented based on the previous blog. If you have not read the previous blog, see the custom AutoCompleteTextView for android development.
The overall effect of this article is shown in:
VcrH1Nq5udTst723qNbQs/XKvLuvxrTS9Lyvus + fuse "brush: java;"> public MyActAdapter(Context context, List books, int maxMatch) { this.books = books; this.context = context; this.maxMatch = maxMatch; initPinYinList(); }
This method initializes two List sets. One is pinYinList and the other is pinYinAllList. The former is the first letter of the pinyin name of the authors of all books, and the latter is the complete pinyin spelling set of the names of the authors of all books.
private void initPinYinList() { pinYinList = new ArrayList
>(); pinYinAllList = new ArrayList
>(); PinYin4j pinyin = new PinYin4j(); for (int i = 0; i < books.size(); i++) { pinYinList.add(pinyin.getPinyin(books.get(i).getAuthor().toString())); pinYinAllList.add(pinyin.getAllPinyin(books.get(i).getAuthor().toString())); } }
Two classes are also involved here, as follows:
PinYin4j. java
Package com. example. myact; import java. util. arrays; import java. util. hashSet; import java. util. set; public class PinYin4j {public PinYin4j () {}/ *** string Set conversion string (separated by commas) ** @ author wangsong * @ param stringSet * @ return */public String makeStringByStringSet (Set
StringSet) {StringBuilder str = new StringBuilder (); int I = 0; for (String s: stringSet) {if (I = stringSet. size ()-1) {str. append (s);} else {str. append (s +,);} I ++;} return str. toString (). toLowerCase ();}/*** obtain Chinese Character pinyin spelling ** @ author wangsong * @ param src * @ return Set
*/Public Set
GetAllPinyin (String src) {char [] srcChar; srcChar = src. toCharArray (); String [] [] temp = new String [src. length ()] []; for (int I = 0; I <srcChar. length; I ++) {char c = srcChar [I]; if (String. valueOf (c ). matches ([\ u4E00-\ u9FA5] +) {String [] t = PinyinHelper. getUnformattedHanyuPinyinStringArray (c); temp [I] = new String [t. length]; for (int j = 0; j
= 65 & (int) c <= 90) | (int) c> = 97 & (int) c <= 122) | c> = 48 & c <= 57 | c = 42) {temp [I] = new String [] {String. valueOf (srcChar [I]) };} else {temp [I] = new String [] {null !}; } String [] pingyinArray = paiLie (temp); return array2Set (pingyinArray);}/*** get the Chinese pinyin initials ** @ author wangsong * @ param src * @ return Set
*/Public Set
GetPinyin (String src) {char [] srcChar; srcChar = src. toCharArray (); String [] [] temp = new String [src. length ()] []; for (int I = 0; I <srcChar. length; I ++) {char c = srcChar [I]; if (String. valueOf (c ). matches ([\ u4E00-\ u9FA5] +) {String [] t = PinyinHelper. getUnformattedHanyuPinyinStringArray (c); temp [I] = new String [t. length]; for (int j = 0; j
= 65 & (int) c <= 90) | (int) c> = 97 & (int) c <= 122) | c> = 48 & c <= 57 | c = 42) {temp [I] = new String [] {String. valueOf (srcChar [I]) };} else {temp [I] = new String [] {null !}; } String [] pingyinArray = paiLie (temp); return array2Set (pingyinArray);}/** evaluate the arrangement and combination of all two-dimensional arrays * For example: {1, 2 }, {3}, {4}, {5, 6} are arranged in two groups: 1345,1346, 2345,2346 */private String [] paiLie (String [] [] str) {int max = 1; for (int I = 0; I
Set
Array2Set (T [] tArray) {Set
TSet = new HashSet
(Arrays. asList (tArray); // TODO does not have a one-step method. Based on the specific function, select the appropriate Set subclass for conversion. Return tSet ;}}
PinyinHelper. java
package com.example.myact;import java.io.BufferedInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Properties;public class PinyinHelper { private static PinyinHelper instance; private Properties properties = null; public static String[] getUnformattedHanyuPinyinStringArray(char ch) { return getInstance().getHanyuPinyinStringArray(ch); } private PinyinHelper() { initResource(); } public static PinyinHelper getInstance() { if (instance == null) { instance = new PinyinHelper(); } return instance; } private void initResource() { try { final String resourceName = /assets/unicode_to_hanyu_pinyin.txt; // final String resourceName = /assets/unicode_py.ini; properties = new Properties(); properties.load(getResourceInputStream(resourceName)); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } private BufferedInputStream getResourceInputStream(String resourceName) { return new BufferedInputStream( PinyinHelper.class.getResourceAsStream(resourceName)); } private String[] getHanyuPinyinStringArray(char ch) { String pinyinRecord = getHanyuPinyinRecordFromChar(ch); if (null != pinyinRecord) { int indexOfLeftBracket = pinyinRecord.indexOf(Field.LEFT_BRACKET); int indexOfRightBracket = pinyinRecord .lastIndexOf(Field.RIGHT_BRACKET); String stripedString = pinyinRecord.substring(indexOfLeftBracket + Field.LEFT_BRACKET.length(), indexOfRightBracket); return stripedString.split(Field.COMMA); } else return null; } private String getHanyuPinyinRecordFromChar(char ch) { int codePointOfChar = ch; String codepointHexStr = Integer.toHexString(codePointOfChar) .toUpperCase(); String foundRecord = properties.getProperty(codepointHexStr); return foundRecord; } class Field { static final String LEFT_BRACKET = (; static final String RIGHT_BRACKET = ); static final String COMMA = ,; } public static String[] toHanyuPinyinStringArray(char ch) { return getUnformattedHanyuPinyinStringArray(ch); }}
This is the initial pinyin set.
The second transformation is to add filtering conditions to the filter.
This is the latest filter. Compared with the previous one, Here we only add an else branch to determine whether the search condition meets the requirements in the else branch.
Private class ArrayFilter extends Filter {@ Override protected FilterResults extends mfiltering (CharSequence constraint) {FilterResults results = new FilterResults (); if (mFilterBooks = null) {mFilterBooks = new ArrayList
(Books);} // if no filter condition exists, if (constraint = null | constraint. length () = 0) {results. values = mFilterBooks; results. count = mFilterBooks. size ();} else {List
RetList = new ArrayList
(); // Filter condition String str = constraint. toString (). toLowerCase (); Book book; // cyclic variable data source. If an attribute meets the filtering conditions, add it to the result for (int I = 0; I <mFilterBooks. size (); I ++) {book = mFilterBooks. get (I); if (book. getAuthor (). contains (str) | book. getName (). contains (str) | (book. getId () + ). contains (str) | (book. getPrice () + ). contains (str) | book. getPinyin (). contains (str) {retList. add (book);} else {// check whether the first letter of the pinyin name of the author meets the filter condition Set
PinyinSet = pinYinList. get (I); Iterator
Pinyin = pinyinSet. iterator (); while (pinyin. hasNext () {if (pinyin. next (). toString (). contains (str) {retList. add (book); break ;}// check whether the pinyin spelling of the author's name meets the filter condition Set
PinyinAllSet = pinYinAllList. get (I); Iterator
PinyinAll = pinyinAllSet. iterator (); while (pinyinAll. hasNext () {if (pinyinAll. next (). toString (). contains (str) {retList. add (book); break ;}}// if (maxMatch> 0) {// if (retList. size ()> maxMatch-1) {// break; //} results. values = retList; results. count = retList. size ();} return results;} // The filter result @ Override protected void publishResults (CharSequence constraint, FilterResults results) is returned here {// notifyDataSetInvalidated (), the control will be repainted (restored to the initial state) // notifyDataSetChanged (), repainting the current visible area books = (List
) Results. values; if (results. count> 0) {policydatasetchanged ();} else {policydatasetinvalidated ();}}}