Examples of displaying contacts in different chapters, quickly sliding listview to display the first letter of a contact, and quickly searching with an alphabet are complicated to view network resources. In particular, some of them also implement the sectionindex interface, many people do not understand it very well. After research, we found that this type of example is not necessary and should not be implemented as such. Here we paste the code for everyone to learn.
1. fastcontactsearchdemoactivity. Java
Package COM. zhf. fastcontactsearchwithalphabeticbardemo; import Java. util. arraylist; import Java. util. collections; import Java. util. hashmap; import Java. util. list; import Java. util. set; import Java. util. regEx. pattern; import COM. zhf. fastcontactsearchdemo. r; 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. view. layoutinflater; import android. view. view; import android. view. viewgroup; import android. widget. baseadapter; import android. widget. listview; import android. widget. textview;/*** example of displaying contacts in different chapters, quickly sliding listview to show the first letter of a contact, and quickly searching with an alphabet * viewing network resources is complicated, in particular, some also implement the sectionindex interface, which many people do not understand very well. The example does not need to be so implemented * @ author hiphonezhu@sina.com **/public class fastcontactsearchdemoactivity extends activity {private baseadapter adapter; private listview personlist; private list <contentvalues> list; private asyncqueryhandler asyncquery; private quickalphabeticbar Alpha; Private Static final string name = "name", number = "Number", sort_key = "sort_key"; @ overridepublic void oncreate (bundle savedinstan Cestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); personlist = (listview) findviewbyid (R. id. listview); alpha = (quickalphabeticbar) findviewbyid (R. id. fast_scroller); asyncquery = new myasyncqueryhandler (getcontentresolver () ;}@ overrideprotected void onresume () {super. onresume (); Uri uri = Uri. parse ("content: // COM. android. contacts/data/phones "); // contact's uristring [] projection = {"_ Id", "display_name", "data1", "sort_key"}; // The queried column asyncquery. startquery (0, null, Uri, projection, null, null, "sort_key collate localized ASC "); // sort by sort_key in ascending order}/*** database asynchronous Query Class asyncqueryhandler ** @ author administrator **/private class myasyncqueryhandler extends asyncqueryhandler {public myasyncqueryhandler (contentresolver Cr) {super (CR) ;}/ *** callback function for query completion */@ overrideprotected void onqueryc Omplete (INT token, object cookie, cursor) {If (cursor! = NULL & cursor. getcount ()> 0) {list = new arraylist <contentvalues> (); cursor. movetofirst (); For (INT I = 0; I <cursor. getcount (); I ++) {contentvalues CV = new contentvalues (); cursor. movetoposition (I); string name = cursor. getstring (1); string number = cursor. getstring (2); string sortkey = cursor. getstring (3); If (number. startswith ("+ 86") {// remove the redundant China region number sign, which has no effect on this program. CV. put (name, name); cv. put (number, number. substring (3); cv. put (sort_key, sortkey);} else {cv. put (name, name); cv. put (number, number); cv. put (sort_key, sortkey);} List. add (CV);} If (list. size ()> 0) {setadapter (list) ;}}} private void setadapter (list <contentvalues> List) {adapter = new listadapter (this, list); personlist. setadapter (adapter); Alpha. init (fastcontactsearchdemoactivity. this); Alpha. setlistview (P Ersonlist); Alpha. sethight (alpha. getheight (); Alpha. setvisibility (view. visible);} Private Static class viewholder {textview Alpha; textview name; textview number ;} /** during transplantation, you only need to provide a list of sorted sets */private class listadapter extends baseadapter {private layoutinflater Inflater; private list <contentvalues> list; private hashmap <string, integer> alphaindexer; // Save the position of each index in the list [#-0, A-4, B-10] private string [] sectio Ns; // index table for each group [a, B, c, f...] public listadapter (context, list <contentvalues> List) {This. inflater = layoutinflater. from (context); this. list = List; // This list is a sorted set. Data in some projects must be sorted by yourself. This. alphaindexer = new hashmap <string, integer> (); this. sections = new string [list. size ()]; for (INT I = 0; I <list. size (); I ++) {string name = getalpha (list. get (I ). getasstring (sort_key); If (! Alphaindexer. containskey (name) {// only records the first occurrence location alphaindexer in the list. put (name, I) ;}}set <string> sectionletters = alphaindexer. keyset (); arraylist <string> sectionlist = new arraylist <string> (sectionletters); collections. sort (sectionlist); sections = new string [sectionlist. size ()]; sectionlist. toarray (sections); Alpha. setalphaindexer (alphaindexer) ;}@ overridepublic int getcount () {return list. size () ;}@ overridepu BLIC object getitem (INT position) {return list. get (position) ;}@ overridepublic long getitemid (INT position) {return position ;}@ overridepublic 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); holde R. name = (textview) convertview. findviewbyid (R. id. name); holder. number = (textview) convertview. findviewbyid (R. id. number); convertview. settag (holder);} else {holder = (viewholder) convertview. gettag ();} contentvalues CV = List. get (position); string name = CV. getasstring (name); string number = CV. getasstring (number); holder. name. settext (name); holder. number. settext (number); // sortkeystring currentst of the current contact R = getalpha (list. Get (position). getasstring (sort_key); // sortkeystring previewstr = (position-1)> = 0? Getalpha (list. Get (position-1). getasstring (sort_key): "";/*** identify the display #, A-Z textview hidden and visible */If (! Previewstr. Equals (currentstr) {// sortkey of the current contact! = Sortkey of the previous contact, indicating that the current contact is in a new group. Holder. alpha. setvisibility (view. visible); holder. alpha. settext (currentstr);} else {holder. alpha. setvisibility (view. gone);} return convertview;}/*** extract the first letter of an English letter. Use # instead of a non-English letter. ** @ Param Str * @ return */private string getalpha (string Str) {If (STR = NULL) {return "#" ;}if (Str. trim (). length () = 0) {return "#";} Char c = Str. trim (). substring (0, 1 ). charat (0); // regular expression to determine whether the first letter is the English letter pattern = pattern. compile ("^ [A-Za-Z] + {1} quot;); If (pattern. matcher (C + ""). matches () {return (C + ""). touppercase (); // uppercase output} else {return "#";}}}
2. quickalphabeticbar. Java
Package COM. zhf. fastcontactsearchwithalphabeticbardemo; import Java. util. hashmap; import COM. zhf. fastcontactsearchdemo. r; import android. app. activity; import android. content. context; import android. OS. handler; import android. util. attributeset; import android. view. motionevent; import android. view. view; import android. widget. imagebutton; import android. widget. listview; import android. widget. textview;/*** alphabet * @ Author hiphonezhu@sina.com **/public class quickalphabeticbar extends imagebutton {private textview mdialogtext; private handler mhandler; private listview MList; private float mhight; 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 hashmap <string, integer> alphain Dexer; Public quickalphabeticbar (context) {super (context);} public quickalphabeticbar (context, attributeset attrs) {super (context, attrs);} public quickalphabeticbar (context, attributeset attrs, int defstyle) {super (context, attrs, defstyle);} public void Init (activity CTX) {mdialogtext = (textview) CTX. findviewbyid (R. id. fast_position); mdialogtext. setvisibility (view. invisible ); Mhandler = new handler ();} public void setlistview (listview MList) {This. MList = MList;} public void setalphaindexer (hashmap <string, integer> alphaindexer) {This. alphaindexer = alphaindexer;} public void sethight (float mhight) {This. mhight = mhight;} @ overridepublic Boolean ontouchevent (motionevent event) {int act = event. getaction (); float y = event. gety (); // calculates the finger position, finds the corresponding segment, and causes the int selectind to be placed at the beginning of the MList moving segment Ex = (INT) (y/(mhight/27); If (selectindex <27) {// prevent cross-border string key = letters [selectindex]; If (alphaindexer. containskey (key) {int Pos = alphaindexer. get (key); If (MList. getheaderviewscount ()> 0) {// prevent listview from having a title bar. In this example, no. This. MList. setselectionfromtop (Pos + MList. getheaderviewscount (), 0);} else {This. MList. setselectionfromtop (Pos, 0);} mdialogtext. settext (letters [selectindex]) ;}} if (Act = motionevent. action_down) {If (mhandler! = NULL) {mhandler. Post (New runnable () {@ overridepublic void run () {If (mdialogtext! = NULL & mdialogtext. getvisibility () = view. invisible) {mdialogtext. setvisibility (visible) ;}}}) ;}} else if (Act = motionevent. action_up) {If (mhandler! = NULL) {mhandler. Post (New runnable () {@ overridepublic void run () {If (mdialogtext! = NULL & mdialogtext. getvisibility () = view. Visible) {mdialogtext. setvisibility (invisible) ;}}}return super. ontouchevent (event );}}
3. layout File
3.1.main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"android:layout_height="fill_parent" android:layout_weight="1.0"> <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="none"android:layout_weight="1.0"android:scrollingCache="true"></ListView><com.zhf.FastContactSearchWithAlphabeticBarDemo.QuickAlphabeticBarandroid:layout_alignRight="@id/listView"android:layout_gravity="top|right|center"android:layout_marginTop="10dip"android:id="@+id/fast_scroller" android:background="@null"android:layout_width="wrap_content" android:layout_height="wrap_content"android:scaleType="centerInside"android:src="@drawable/dic_background" /><TextViewandroid:layout_centerInParent="true" android:id="@+id/fast_position" android:textSize="48dip" android:visibility="invisible"android:textColor="#404040" android:background="@drawable/sort_icon_bg_click"android:layout_gravity="center_horizontal|top" android:padding="2dip"android:layout_margin="34dip" android:layout_width="70dip"android:layout_height="70dip" android:gravity="center" /></RelativeLayout>
3.2.list _ item. 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"> <! -- Initials --> <textview Android: Id = "@ + ID/Alpha" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: background = "#333333" Android: paddingleft = "10dip" Android: textcolor = "# ffffff" Android: visibility = "gone"/> <! -- Contact Information --> <imageview Android: Id = "@ + ID/imageview" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_alignparentleft = "true" Android: layout_below = "@ ID/Alpha" Android: src = "@ drawable/ic_launcher"/> <textview Android: id = "@ + ID/Name" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_aligntop = "@ ID/imageview" Android: layout_margi Nleft = "2.0dip" Android: layout_marginright = "5.0dip" Android: layout_margintop = "6.0dip" Android: layout_torightof = "@ ID/imageview" Android: singleline = "true" Android: textappearance = "? Android: textappearancemedium "/> <textview Android: Id =" @ + ID/number "Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "Android: layout_alignleft = "@ ID/Name" Android: layout_alignwithparentifmissing = "true" Android: layout_below = "@ ID/Name" Android: ellipsize = "marquee" Android: singleline = "true" Android: textappearance = "? Android: textappearancesmall "/> </relativelayout>
4.
Source Code address: http://download.csdn.net/detail/zhf198909/4485281