Android Imitation micro-letter implementation of the first-letter navigation bar _android

Source: Internet
Author: User
Tags lowercase stringbuffer

This article introduces the Android implementation of the first letter navigation bar, first look at the picture, how to implement the code to see

The specific steps

1. Overall layout of the display
2. Realize A-Z grouping
3. Customize A-Z navigation bar
4. The middle show/hide touch to the navigation bar specific letters

Activity_main.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout 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= "#fff" android:orientation= "vertical" tools:context= " Com.example.firstnavigation.MainActivity "> <framelayout android:layout_width=" match_parent "Android:layout_ height= "Wrap_content" > <!--listview--> <listview android:id= "@+id/friend_listview" Android:layout_ Width= "Match_parent" android:layout_height= "wrap_content" android:layout_gravity= "center"/> <!--in the middle of the letter--&

  Gt <textview android:id= "@+id/tv_first" android:layout_width= "80DP" android:layout_height= "80DP" android:layou t_gravity= "center" android:text= "A" android:textcolor= "#ff0000" android:textsize= "30sp" android:visibility= "Go Ne "/> <!--custom navigation bar--> <com.example.firstnavigatIon. Slidview android:id= "@+id/slidview" android:layout_width= "30DP" android:layout_height= "Match_parent" android:l

 ayout_gravity= "Right|center"/> </FrameLayout> </LinearLayout>

item.xml--"ListView corresponding 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=" Match_parent "
 android: Background= "#fff"
 android:orientation= "vertical" >

 <!--first letter-->

 <textview
  android:id = "@+id/tv"
  android:layout_width= "match_parent"
  android:layout_height= "Wrap_content"
  android: Background= "#9e9d9d"
  android:textcolor= "#fff"
  android:textsize= "16sp"/> The

 first Chinese character corresponding to the first letter of the!--- >

 <textview
  android:id= "@+id/name"
  android:layout_width= "Wrap_content"
  android: layout_height= "Wrap_content"
  android:textcolor= "#262626"
  android:textsize= "16sp"/>
</ Linearlayout>

Contact Bean

public class Contacts {
 //name
 private String name;
 The first letter of the name is
 private String FirstWord;

 Public String GetName () {return
  name;
 }

 public void SetName (String name) {
  this.name = name;
 }

 Public String Getfirstword () {return
  firstword;
 }

 public void Setfirstword (String ch) {
  This.firstword = ch;
 }
}

Contactadapter.java

public class Contactadapter extends Baseadapter {private arraylist<contact> ArrayList;
 private context;

 Private String pre = "A";
  Public Contactadapter (arraylist<contact> ArrayList) {this.arraylist = ArrayList;
 This.context = context;
 @Override public int GetCount () {return arraylist.size ();
 @Override public Object getitem (int position) {return arraylist.get (position);
 @Override public long getitemid (int position) {return position;
  @Override public View getview (int position, View Convertview, ViewGroup parent) {Viewholder viewholder;
   if (Convertview = = null) {Viewholder = new Viewholder ();
   Convertview = Layoutinflater.from (context). Inflate (R.layout.item, parent, false);
   Viewholder.tv_firstword = (TextView) Convertview.findviewbyid (r.id.tv);
   Viewholder.name = (TextView) Convertview.findviewbyid (r.id.name);
  Convertview.settag (Viewholder); else {Viewholder = (Viewholder) CONVERTVIew.gettag ();
  } viewHolder.tv_firstWord.setText (String.valueof (arraylist.get (position). Getfirstword ()));
  ViewHolder.name.setText (Arraylist.get (position). GetName ()); /** * Group: According to the first letter of Chinese characters/viewHolder.tv_firstWord.setVisibility (!arraylist.get (position) Getfirstword (). Equals (PRE)? Iew.
  VISIBLE:View.GONE);
  Pre = Arraylist.get (position). Getfirstword ();
 return convertview;
  Class Viewholder {TextView Tv_firstword;
 TextView name;

 }

Mainactivity

public class Mainactivity extends Appcompatactivity {private ListView ListView;
 Private TextView Tv_first;
 Private arraylist<contact> contacts;

 Private Slidview Slidview;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Initview ();
 InitData ();
  private void Initview () {ListView = (ListView) Findviewbyid (R.id.friend_listview);
  Tv_first = (TextView) Findviewbyid (R.id.tv_first);
  Slidview = (Slidview) Findviewbyid (R.id.slidview); Slidview.setfirstlistener (New Ontouchfirstlistener () {@Override public void Ontouch (String str) {Tv_first.setv
    Isibility (view.visible);
    Tv_first.settext (str); for (int i = 0; i < contacts.size (); i++) {if str.equals (Contacts.get (i). Getfirstword ()) {Listview.setse
     Lection (i);
     @Override public void Onrelease ()} {new Handler (). postdelayed () (new Runnable () {@Override PublIC void Run () {tv_first.setvisibility (view.gone);
   }, 300);
 }
  });
  private void InitData () {contacts = new arraylist<> ();
  Gets the character array resource string[] Attrs = Getresources (). Getstringarray (R.array.myfriend);
  Contact contacts;
   for (int i = 0; i < attrs.length i++) {contacts = new contact ();
   Contact.setname (Attrs[i]);
   Contact.setfirstword (Getpinyinheadchar (Attrs[i], 2));
  Contacts.add (contact);  //Sort A-Z collections.sort (Contacts, new comparator<contact> () {@Override public int compare (Contact LHS,
   Contact RHS) {return Lhs.getfirstword (). CompareTo (Rhs.getfirstword ());
  }
  });
  Contactadapter contactadapter = new Contactadapter (contacts, this);
 Listview.setadapter (Contactadapter);
  /** * Extracts the first letter of the Chinese character, if it contains a fee, the text is ignored; if all is not Chinese then return "".
  * * @param casetype when the first letter obtained for 1 o'clock is lowercase, it is uppercase. */public static string Getpinyinheadchar (string zn_str, int casetype) {if (zn_str!= null &&!zn_str.trim (). E QualsignorecasE ("")) {char[] Strchar = Zn_str.tochararray ();
   Hanyu Pinyin format Output class Hanyupinyinoutputformat Hanyupinoutputformat = new Hanyupinyinoutputformat ();
   Output settings, case, phonetic mode, etc. if (1 = casetype) {hanyupinoutputformat.setcasetype (hanyupinyincasetype.lowercase);
   else {hanyupinoutputformat.setcasetype (hanyupinyincasetype.uppercase);
   } hanyupinoutputformat.settonetype (Hanyupinyintonetype.without_tone);
   Hanyupinoutputformat.setvchartype (HANYUPINYINVCHARTYPE.WITH_V);
   StringBuffer pystringbuffer = new StringBuffer ();
   char C = strchar[0];
   Char PYc; if (string.valueof (c). Matches ("[\\u4e00-\\u9fa5]+")) {//is Chinese or a-Z or a-z convert pinyin try {string[] Pystirngarray = Pinyinhe
     Lper.tohanyupinyinstringarray (Strchar[0], hanyupinoutputformat);
      if (null!= pystirngarray && pystirngarray[0]!= null) {PYC = Pystirngarray[0].charat (0);
     Pystringbuffer.append (PYC);
 } catch (Badhanyupinyinoutputformatcombination e) {e.printstacktrace ();   } return pystringbuffer.tostring ();
 return null;

 }

Extract the first letter need to use the Pingyin4j.jar, small knitting is not available in this, you can download online

Custom Letter navigation control public class Slidview extends View {private string[] STRs = {"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;

 Private Ontouchfirstlistener listener;
 Public Slidview {This (context, NULL);
 Public Slidview (context, AttributeSet attrs) {This (context, attrs, 0);
  Public Slidview (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);
  Paint = new paint ();
  Paint.setantialias (TRUE);
  Paint.setcolor (Color.gray);

 Paint.settypeface (Typeface.default_bold);  }//PX----&GT;SP protected int sp2px (int spval) {return (int) typedvalue.applydimension (typedvalue.complex_unit_sp,
 Spval, Getresources (). Getdisplaymetrics ());
  } @Override protected void OnDraw (Canvas Canvas) {Super.ondraw (Canvas); for (int i = 0; i < strs.length i++) {Paint.setcolor (i = = index?) Color.RED:ColOr.
   Black);
   Paint.settextsize (i = = Index sp2px (a): sp2px (16));
   int x = (int) (GetWidth ()-Paint.measuretext (Strs[i]))/2;
   int y = getheight ()/strs.length * (i + 1);
  Canvas.drawtext (Strs[i], x, y, paint); } int index =-1; Get touch to alphabetical position//Touch Event//Press, release, drag @Override public boolean ontouchevent (Motionevent event) {switch (event.getaction
    ()) {case MotionEvent.ACTION_DOWN:case MotionEvent.ACTION_MOVE:float y = event.gety ();
    This.setbackgroundcolor (Color.gray);
    Gets the position of the touch to the letter index = (int) y * strs.length/getheight ();
    Listener.ontouch (Strs[index]);
   Break Case MotionEvent.ACTION_UP:this.setBackgroundColor (Android.
    R.color.transparent);
    index =-1;
    Listener.onrelease ();
  Break
  //Redraw invalidate ();
 return true;
 public void Setfirstlistener (Ontouchfirstlistener listener) {This.listener = listener; }/** * Ontouchfirstlistener interface * Ontouch: Touch the letter * Onrelease:up release the letters in the middle should be set to gone * pUblic interface Ontouchfirstlistener {void Ontouch (String ch);
void Onrelease ();


 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.