Reprinted please indicate the source: http://blog.csdn.net/guolin_blog/article/details/9050671
In the previous article, I worked with you to implement the grouping navigation and extrusion animation functions similar to Android system contacts. However, since the article is named "full effect for contacts in Android system", if there is no quick rolling function, it is obviously not "full. Therefore, this article will lead you to improve the code of the previous article and add the quick scrolling function.
If you have not read my previous article, please read it now.Full special effects (on) of contacts in the Android system, grouping navigation, and extrusion animation.
In fact, listview itself has a fast rolling attribute, which can be enabled by setting Android: fastscrollenabled = "true" in XML. This method is used in earlier Android contacts for quick scrolling. Shows the effect:
However, this fast rolling method is ugly, and many mobile phone manufacturers later in the customization of their Rom will default fast rolling into a similar iPhone A-Z alphabet quick rolling method. How can we lag behind the times! Our quick scrolling will also use the A-Z alphabet!
Next we will start to implement it. First open the last contactsdemo project and modify the activity_main.xml layout file. Since we want to add the alphabet to the interface, we need a button, set the background of this button to an image sorted by a A-Z, and then right-aligned. In addition, a textview is required to display the current group in the pop-up group layout. The default value is gone, which is displayed only when the finger slides on the alphabet. The modified layout file code is as follows:
<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:orientation="vertical" > <ListView android:id="@+id/contacts_list_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:scrollbars="none" android:fadingEdge="none" > </ListView> <LinearLayout android:id="@+id/title_layout" android:layout_width="fill_parent" android:layout_height="18dip" android:layout_alignParentTop="true" android:background="#303030" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginLeft="10dip" android:textColor="#ffffff" android:textSize="13sp" /> </LinearLayout> <Button android:id="@+id/alphabetButton" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/a_z" /> <RelativeLayout android:id="@+id/section_toast_layout" android:layout_width="70dip" android:layout_height="70dip" android:layout_centerInParent="true" android:background="@drawable/section_toast" android:visibility="gone" > <TextView android:id="@+id/section_toast_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="#fff" android:textSize="30sp" /> </RelativeLayout></RelativeLayout>
Then open mainactivity and modify it. Without a doubt, we need to listen to the touch event of the alphabet button, so we add the following code in mainactivity:
private void setAlpabetListener() {alphabetButton.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {float alphabetHeight = alphabetButton.getHeight();float y = event.getY();int sectionPosition = (int) ((y / alphabetHeight) / (1f / 27f));if (sectionPosition < 0) {sectionPosition = 0;} else if (sectionPosition > 26) {sectionPosition = 26;}String sectionLetter = String.valueOf(alphabet.charAt(sectionPosition));int position = indexer.getPositionForSection(sectionPosition);switch (event.getAction()) {case MotionEvent.ACTION_DOWN:alphabetButton.setBackgroundResource(R.drawable.a_z_click);sectionToastLayout.setVisibility(View.VISIBLE);sectionToastText.setText(sectionLetter);contactsListView.setSelection(position);break;case MotionEvent.ACTION_MOVE:sectionToastText.setText(sectionLetter);contactsListView.setSelection(position);break;default:alphabetButton.setBackgroundResource(R.drawable.a_z);sectionToastLayout.setVisibility(View.GONE);}return true;}});}
We can see that in this method we have registered the ontouch event of the alphabet button, and then made some logical judgment and processing in the ontouch method. I will explain it in detail below. First, get the total height of the alphabet through the getheight method of the alphabet button, and then use event. the Gety method obtains the Y coordinate of the current finger on the alphabet. By dividing the Y coordinate by the total height, you can obtain the position of the current finger represented by decimal places (0 table at # end, 1 indicates on the Z end ). Since we have a total of 27 characters in the alphabet, we can use the calculated decimal number and divide it by 1/27 to get a floating point number ranging from 0 to 27, and then round down the floating point number, then we can figure out the letter on which we are currently pressing. Then, judge the action of the event. If it is action_down or action_move, the pop-up group will display the letter of the current finger, call the setselection method of listview to scroll the list to the corresponding group. For other actions, the pop-up group layout is hidden.
The complete mainactivity code is as follows:
Public class mainactivity extends activity {/*** group Layout */private linearlayout titlelayout;/*** pop-up group Layout */private relativelayout sectiontoastlayout; /** sliding alphabet */private button alphabetbutton on the right side;/* The letter displayed on the Group */private textview title; /*** text in the pop-up group */private textview sectiontoasttext;/*** contact listview */private listview contactslistview;/*** contact list adapter */private contactadapter adapter; /*** Alphabet Group */private alphabetindexer indexer;/*** stores contacts in all mobile phones */private list <contact> contacts = new arraylist <contact> (); /*** define the sorting rule of the alphabet */private string alphabet = "# abcdefghijklmnopqrstuvwxyz";/*** the first visible element used to record the identifier during scrolling. */Private int lastfirstvisibleitem =-1; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); adapter = new contactadapter (this, R. layout. contact_item, contacts); titlelayout = (linearlayout) findviewbyid (R. id. title_layout); sectiontoastlayout = (relativelayout) findviewbyid (R. id. section_toast_layout); Title = (textview) Findviewbyid (R. id. title); sectiontoasttext = (textview) findviewbyid (R. id. section_toast_text); alphabetbutton = (button) findviewbyid (R. id. alphabetbutton); contactslistview = (listview) findviewbyid (R. id. contacts_list_view); Uri uri = contactscontract. commondatakinds. phone. content_uri; cursor = getcontentresolver (). query (Uri, new string [] {"display_name", "sort_key"}, null, null, "sort_key"); I F (cursor. movetofirst () {do {string name = cursor. getstring (0); string sortkey = getsortkey (cursor. getstring (1); contact = new contact (); contact. setname (name); contact. setsortkey (sortkey); contacts. add (contact);} while (cursor. movetonext ();} startmanagingcursor (cursor); indexer = new alphabetindexer (cursor, 1, alphabet); adapter. setindexer (Indexer); If (contacts. size ()> 0) {setupcontactslistvi EW (); setalpabetlistener () ;}/ *** sets a listener event for the contact listview, and changes the display position of the group based on the current sliding status to achieve the effect of extrusion animation. */Private void setupcontactslistview () {contactslistview. setadapter (adapter); contactslistview. listener (New onscrolllistener () {@ overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {}@ overridepublic void onscroll (abslistview view, int cursor, int visibleitemcount, int totalitemcount) {int section = indexer. getsectionforposition (firstvisibleitem); int nexts Ecposition = indexer. getpositionforsection (section + 1); If (firstvisibleitem! = Lastfirstvisibleitem) {marginlayoutparams Params = (marginlayoutparams) titlelayout. getlayoutparams (); Params. topmargin = 0; titlelayout. setlayoutparams (Params); title. settext (string. valueof (alphabet. charat (section);} If (nextsecposition = firstvisibleitem + 1) {view childview = view. getchildat (0); If (childview! = NULL) {int titleheight = titlelayout. getheight (); int Bottom = childview. getbottom (); marginlayoutparams Params = (marginlayoutparams) titlelayout. getlayoutparams (); If (bottom <titleheight) {float pusheddistance = bottom-titleheight; Params. topmargin = (INT) pusheddistance; titlelayout. setlayoutparams (Params);} else {If (Params. topmargin! = 0) {Params. topmargin = 0; titlelayout. setlayoutparams (Params) ;}}} lastfirstvisibleitem = firstvisibleitem ;}});}/*** sets the touch events of the alphabet, and combines the height of the alphabet according to the current touch position, calculate the letter of the current touch. * When the finger is pressed to the alphabet, the pop-up group is displayed. Hide the pop-up group when the finger leaves the alphabet. */Private void setalpabetlistener () {alphabetbutton. setontouchlistener (New ontouchlistener () {@ overridepublic Boolean ontouch (view V, motionevent event) {float alphabetheight = alphabetbutton. getheight (); float y = event. gety (); int sectionposition = (INT) (y/alphabetheight)/(1f/27F); If (sectionposition <0) {sectionposition = 0 ;} else if (sectionposition> 26) {sectionposition = 26;} string Sectionletter = string. valueof (alphabet. charat (sectionposition); int position = indexer. getpositionforsection (sectionposition); Switch (event. getaction () {Case motionevent. action_down: alphabetbutton. setbackgroundresource (R. drawable. a_z_click); sectiontoastlayout. setvisibility (view. visible); sectiontoasttext. settext (sectionletter); contactslistview. setselection (position); break; Case motionevent. action _ Move: sectiontoasttext. settext (sectionletter); contactslistview. setselection (position); break; default: alphabetbutton. setbackgroundresource (R. drawable. a_z); sectiontoastlayout. setvisibility (view. gone) ;}return true ;}}) ;}/ *** get the first character of the sort key. If it is an English letter, return directly; otherwise, return #. ** @ Param sortkeystring * the sort key read from the database * @ return English letter or # */private string getsortkey (string sortkeystring) {alphabetbutton. getheight (); string key = sortkeystring. substring (0, 1 ). touppercase (); If (key. matches ("[A-Z]") {return key;} return "#";}}
Now, we have changed the above two parts, and the other files remain unchanged. Let's run it to see the effect:
Very good! When your fingers slide on the right alphabet, the contact list also changes accordingly and displays a current group in the center of the screen.
Now let's count back, group navigation, squeeze animation, and quick alphabet scrolling. All the special effects of contacts in the Android system are achieved!
Now, today's explanation is over. If you have any questions, please leave a message below.
Click here to download the source code