Android Mobile Contact Quick Index (mobile newsletter) _android

Source: Internet
Author: User

Recently need to implement a mobile phone address Book fast indexing function. Fast indexing function based on first letter of name. Below is a mobile phone contact Quick Index effect, the overall code is not difficult, pinyin conversion place slightly complex. The following source code: The source code has comments.

Here is the effect chart:

Mainactivity:

Import java.util.ArrayList;
Import java.util.Collections;
Import java.util.List;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.BaseAdapter;
Import Android.widget.ListView;
Import Android.widget.TextView;
 /** * This is the main layout * @author LXD * * * * * * */public class Mainactivity extends activity {private ListView lv_main;
 Private Friendadapter adapter;
 Private list<friend> data = new arraylist<friend> ();
 Private Quickindexview Qiv_main;
 Private TextView Tv_main_word; Private Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {//Hide word Tv_main_word
  . setvisibility (View.gone);
 }
 };
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Lv_main = (ListView) Findviewbyid (R.id.lv_main); Qiv_main = (Quickindexview) Findviewbyid (r.id.qiv_main);
  Tv_main_word = (TextView) Findviewbyid (R.id.tv_main_word); Sets the Listener Qiv_main.setonindexchangedlistener (new Quickindexview.onindexchangedlistener () {@Override public void Onin
    Dexchanged (String Word) {tv_main_word.settext (word);
    Tv_main_word.setvisibility (view.visible);
    Handler.removemessages (1);
    Remove the unhandled message handler.removecallbacksandmessages (NULL);
    Send Delay Message handler.sendemptymessagedelayed (1, 2000); Slide ListView//Find the corresponding item for (int i=0;i<data.size (); i++) {String Fword = Data.get (i). Getpinyin (). substring
     (0, 1);
      if (Word.equals (Fword)) {lv_main.setselection (i);
     Return
   @Override public void Onup () {//tv_main_word.setvisibility (view.gone);
  }
  });
  Display list adapter = new Friendadapter ();
  InitData ();
  Lv_main.setadapter (adapter);
 Lv_main.setselection (5);
  private void InitData () {Data.add (New Friend ("John"));
  Data.add (New Friend ("Yang Jiu")); Data.add (New Friend ("Hu Jiqun"));
  Data.add (New Friend ("Liu Chang"));
  Data.add (New Friend ("Zhong Zehing"));
  Data.add (New Friend ("Yin Innovation");
  Data.add (New Friend ("An"));
  Data.add (New Friend ("Zhangqian"));
  Data.add (New Friend ("Winson"));
  Data.add (New Friend ("Li Fengqiu"));
  Data.add (New Friend ("Liu Fu"));
  Data.add (New Friend ("Lou Quan Ultra"));
  Data.add (New Friend ("Zhang Meng"));
  Data.add (New Friend ("Wang Yingjie"));
  Data.add (New Friend ("Li Zhennan"));
  Data.add (New Friend ("Sun Ren"));
  Data.add (New Friend ("Tang Spring Thunder"));
  Data.add (New Friend ("Neu Pengwei"));
  Data.add (New Friend ("Ginger Aerospace"));
  Data.add (New Friend ("Liu Yan"));
  Data.add (New Friend ("Zhang Hongrui"));
  Data.add (New Friend ("Zhangjianzhong"));
  Data.add (New Friend ("Houya Handsome"));
  Data.add (New Friend ("Liu Shuai"));
  Data.add (New Friend ("Joe Flying"));
  Data.add (New Friend ("Xu Yujian"));
  Data.add (New Friend ("Wuliang"));
  Data.add (New Friend ("Wang Zhaolin"));
  Data.add (New Friend ("a third");
 Collections.sort (data);
  Class Friendadapter extends Baseadapter {@Override public int getcount () {return data.size (); @Override public Object getitem (int position) {returnData.get (position);
  @Override public long getitemid (int position) {return 0;
   @Override public View getview (int position, View Convertview, ViewGroup parent) {Viewholder holder = null;
    if (convertview==null) {holder = new Viewholder ();
    Convertview = View.inflate (mainactivity.this, r.layout.item_main, NULL);
    HOLDER.WORDTV = (TextView) Convertview.findviewbyid (R.id.tv_item_word);
    Holder.nametv = (TextView) Convertview.findviewbyid (r.id.tv_item_name);
   Convertview.settag (holder);//***********?
   else {holder = (Viewholder) convertview.gettag ();
   Friend friend = Data.get (position);
   String Word = Friend.getpinyin (). substring (0, 1);
   Holder.wordTV.setText (word);
   Holder.nameTV.setText (Friend.getname ());
   The display if (position==0) {holder.wordTV.setVisibility (view.visible) with subscript 0;
    else {//Remove the last friend and get the first word String Preword = Data.get (position-1). Getpinyin (). substring (0, 1); Determines whether word is the same on the current line//If the same, hide if (word.equals (Preword)) {holder.wordTV.setVisibility (view.gone);
    else {//if different, show holder.wordTV.setVisibility (view.visible);
  } return Convertview;
   Class Viewholder {public TextView wordtv;
  Public TextView Nametv; }
 }
}

Master layout:

<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 "Tools:context" = "${relativepackage}.${activityclass}" > <listview android:id= "@+id/lv_main android:layout_width=" Match_ Parent "android:layout_height=" match_parent "> </ListView> <!--com.atguigu.quickindex.QuickIndexView-- > <com.atguigu.quickindex.quickindexview android:id= "@+id/qiv_main" android:layout_width= "40DP" Android:layo ut_height= "Match_parent" android:layout_alignparentright= "true" android:background= "#ffffff" > </ com.atguigu.quickindex.quickindexview> <textview android:id= "@+id/tv_main_word" android:layout_width= "100DP "Android:layout_height=" 100DP "android:layout_centerhorizontal=" true "android:layout_centervertical=" true "Androi D:background= "#66666666" android:text= "A" android:textsize= "40SP" Android:gravity= "center" android:visibility= "Gone"/> </RelativeLayout> 

Item:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
 android:layout_width=" match_parent "
 android:layout_height=" wrap_content "
 android:o" rientation= "vertical" >
 <textview
  android:id= "@+id/tv_item_word" android:layout_width= "Fill_"
  Parent "
  android:layout_height=" wrap_content "
  android:text=" A " 
  android:background=" #66666666 "
  android:textsize= "18SP"
  android:padding= "5DP"/>
 <textview
  android:id= "@+id/tv_item_" Name "
  android:layout_width=" fill_parent "
  android:layout_height=" wrap_content "
  android:text=" Someone " 
  android:textsize= "18SP"
  android:padding= "5DP"/>
</LinearLayout>

Custom View:

Import Android.content.Context;
Import Android.graphics.Canvas;
Import Android.graphics.Color;
Import Android.graphics.Paint;
Import Android.graphics.Rect;
Import Android.util.AttributeSet;
Import android.view.MotionEvent;
Import Android.view.View;
 /** * This is a custom view * @author LXD * */public class Quickindexview extends view {private float itemwidth;
 private float itemheight;
 private float wordwidth;
 private float wordheight;  Private string[] Indexarr = {"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 Paint Paint;
  Public Quickindexview (context, AttributeSet attrs) {Super (context, attrs);
  Paint = new paint ();
  Paint.setcolor (Color.White);
  Paint.settextsize (16);
 Paint.setantialias (TRUE); @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec,
  HEIGHTMEASURESPEC); Itemwidth = This.getmeasuRedwidth ();
 ItemHeight = This.getmeasuredheight ()/26f; @Override protected void OnDraw (Canvas Canvas) {//When the redraw is triggered each time, 26 letters are cycled over for (int i = 0; i < indexarr.length;
   i++) {String word = indexarr[i];
    Set the color of the text if (i = = Touchindex) {//Here set the changed letters to be clicked: The color turns gray, the font changes to 25SP paint.setcolor (Color.gray);
   Paint.settextsize (25);
    else {//other not clicked letters, keep the original status: Set the color, font size of 18sp paint.setcolor (Color.Black);
   Paint.settextsize (18);
   ///Get Word's wide-high Rect bounds = new Rect ();
   Paint.gettextbounds (Word, 0, word.length (), bounds);
   Get the wide int wordwidth = Bounds.width () of the font;
   Get the font of high int wordheight = Bounds.height ();
   Calculates the coordinates of Word's upper-left corner: The x coordinate of the letter, the y-coordinate float x = ITEMWIDTH/2-WORDWIDTH/2;
   Float y = itemheight/2 + wordheight/2 + i * itemheight;
  Draw Word Canvas.drawtext (Word, x, y, paint);
 }/////////////////////////////////////////////////////////////////////////private int touchindex = subscript for -1;//Touch letters @Override public BoOlean Ontouchevent (Motionevent event) {//Get events coordinates float Eventy = event.gety (); Switch (event.getaction ()) {case MotionEvent.ACTION_DOWN:case Motionevent.action_move://calculate subscript int index = (in
   T) (eventy/itemheight);
   if (Index >) {index = 25;
   } if (Index < 0) {index = 0;
    ///If subscript has changed, force redraw if (index!= touchindex) {//update touchindex touchindex = index;
    Force redraw invalidate (); Notifies the activity update TextView if (Onindexchangedlistener!= null) {onindexchangedlistener.onindexchanged (Indexarr[inde
    X]);
  }} break;
   Case MotionEvent.ACTION_UP:touchIndex =-1;
   Force redraw invalidate ();
   Notifies the activity update TextView if (Onindexchangedlistener!= null) {onindexchangedlistener.onup ();
  } break;
  Default:break;
 Return true;//All events are consumed by the current view} private Onindexchangedlistener Onindexchangedlistener; * * Set the method of listening object This method is typically an activity call/public void Setonindexchangedlistener (ONINDEXCHangedlistener onindexchangedlistener) {this.onindexchangedlistener = Onindexchangedlistener;
  Interface Onindexchangedlistener {////when the subscript for the operation changes, the public void onindexchanged (String word) is automatically invoked;
 Call public void Onup () when up; }
}

Contact Human:

/** *
 Contact Human
 * @author LXD * */Public
class Friend implements comparable<friend> {
 private String name;
 private String Pinyin;
 Public Friend (String name) {
  super ();
  this.name = name;
  Pinyin = Pinyinutils.getpinyin (name);
 }
 Public String GetName () {return
  name;
 }
 public void SetName (String name) {
  this.name = name;
 }
 Public String Getpinyin () {return
  pinyin;
 }
 public void Setpinyin (String pinyin) {
  this.pinyin = pinyin;
 }
 @Override public
 String toString () {return
  "Friend [name=" + name + ", pinyin=" + pinyin + "]";
 }
 @Override public
 int CompareTo (Friend another) {return
  This.pinyin.compareTo (Another.getpinyin ());
 }
}

Tool class: Used to convert Chinese characters to pinyin

/** * Converts Chinese characters to pinyin * @author LXD * */public class Pinyinutils {/** * to get the pinyin of the specified kanji * Note: should not be called frequently, it consumes a certain amount of memory * @param ha
  Nzi * @return/public static string Getpinyin (String hanzi) {string pinyin = ""; Hanyupinyinoutputformat format = new Hanyupinyinoutputformat ()//control whether the conversion is case or not, Shiying label Format.setcasetype (
  Hanyupinyincasetype.uppercase);//Capital Format.settonetype (Hanyupinyintonetype.without_tone);
  Since it cannot be directly converted to multiple Chinese characters, only a single Chinese character can be converted to char[] arr = Hanzi.tochararray (); for (int i = 0; i < arr.length i++) {if (Character.iswhitespace (arr[i)) continue;//If the space is not processed, the next traversal//Kanji is 2 bytes stored is definitely greater than 127, so greater than 127 can be converted to kanji if (arr[i]>127) {try {//due to the existence of pronunciation, Dan shan string[] Pinyinarr = Pinyinhelpe
     R.tohanyupinyinstringarray (Arr[i], format);
     if (pinyinarr!=null) {pinyin + = pinyinarr[0];
     }else {Pinyin + = arr[i];
     } catch (Badhanyupinyinoutputformatcombination e) {e.printstacktrace ();
    Not the correct kanji pinyin + = arr[i];
 }}else {   Not Chinese characters, pinyin + = arr[i];
 } return pinyin; }
}

The above code is about the Android phone Contact Quick index (mobile phone records) of the full description, I hope you like.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.