Android Custom View implements the letter navigation bar _android

Source: Internet
Author: User
Tags drawtext

A lot of Android Getting Started program apes may be more fearful about Android custom view, but this is the only way to get to the master's level, all ready to spend some time on custom view and write more articles.

Thinking Analysis:

1, custom View implementation of the letter navigation bar

2, ListView Implementation Contact list

3, the letter navigation bar Sliding event handling

4, the letter navigation bar and the middle letter linkage

5. The linkage between the letter navigation bar and the ListView

Effect Chart:

First, we first throw out the main layout file, easy to explain the following code

<!--? XML version= "1.0" encoding= "Utf-8"?--> <linearlayout android:layout_height= "match_parent" Android: Layout_width= "match_parent" android:orientation= "vertical" xmlns:android= "http://schemas.android.com/apk/res/" Android "> <edittext android:background=" @drawable/search_border "android:drawableleft=" @android:d rawable/ic 
 _menu_search "android:layout_height=" wrap_content "android:layout_width=" match_parent "android:padding=" 8DP "> <relativelayout android:layout_height= "match_parent" android:layout_width= "match_parent" > <listview Android:divider= "@null" android:id= "@+id/lv" android:layout_height= "match_parent" android:layout_width= "Match_" Parent "> <textview android:background=" "#888888" android:gravity= "center" android:id= "@+id/tv" Android:layout_ Centerinparent= "true" android:layout_height= "50DP" android:layout_width= "50DP" android:textcolor= "#000000" Android : textsize= "18DP" android:visibility= "Gone" > <com.handsome.tulin.view.navview android:id="@+id/nv" android:layout_alignparentright= "true" android:layout_height= "Match_parent" android:layout_margin= "16DP "Android:layout_width=" 20DP > </com.handsome.tulin.view.navview></textview></listview><
 /relativelayout> </edittext></linearlayout>

Step one: Analyze the custom letter navigation bar

Thinking Analysis:

1, we use the time to set the width to 20DP, high set to fill the parent control, so the width of the obtained here is 20DP

2, through the loop, draw the vertical letter, each time you have to reset the color, because we need a selected letter color and the default is not the same

public class Navview extends View {private Paint textpaint = new Paint (); Private string[] s = 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 "," # "};
 Mouse clicks, sliding when the selected letter private int choose =-1;
 The middle text private TextView TV;
 Public Navview (context, AttributeSet attrs) {Super (context, attrs);
 Public Navview {Super (context);
 Public Navview (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);
  private void Initpaint () {textpaint.settextsize (20);
  Textpaint.setantialias (TRUE);
 Textpaint.setcolor (Color.Black);
  } @Override protected void OnDraw (Canvas Canvas) {Super.ondraw (Canvas);
 Draw Letter DrawText (canvas);
  /** * Draw Letter * * @param canvas/private void DrawText (canvas canvas) {//Get view's wide-high int width = getwidth ();
  int height = getheight (); Gets the height of each letter int SingleheiGht = Height/s.length;
   Draw letter for (int i = 0; i < s.length i++) {//brush default color Initpaint ();
   Highlight Letter Color if (choose = i) {textpaint.setcolor (color.red);
   //Calculate the coordinates of each letter float x = (Width-textpaint.measuretext (s[i]))/2;
   Float y = (i + 1) * singleheight;
   Canvas.drawtext (S[i], x, y, textpaint);
  Reset color Textpaint.reset ();
 }
 }
}

Step Two: ListView Implement contact List

Thinking Analysis:

1. In the main activity, define an array of data, use the tool class to get the first letter of the array, use collections to sort by the first letter, because the tool class is a bit long, it is not posted.

2, create a ListView child layout, create a adapter to fill.

Master layout:

public class Mainactivity extends appcompatactivity {private TextView TV;
 Private ListView LV;
 Private Navview NV;
 Private list<user> List;
 Private Useradapter adapter; Private string[] name = new string[]{"Pan Yue Ming", "Dai Jun", "Shiri", "Blue Rain", "Ningquan", "Zhang Jie", "Qin Junjie", "Chen Kun", "Tian", "Summer Rain", "Baojian", "Lu Yi", "Joe Zhen Yu "," Gije "," Guo "," Huddivan "," Huanhuan "," Stubbornness Jingboran "," Zo Xiaozu mantra "," Duan Yihong "," Mao Ning "," Fanfan "," Soup Tide "," Mountain "," Minkovitz "," Hou Yong "," Youseian "," Feng Shao "," Cui Jian "," Du Chun ","
 Zhang Han "," Pentan "," Cypress "," Buba "," Lingxiaosu "," Mao Fangyuan "," Martial Arts "," Geng le "," Chan "};
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Initview ();
 InitData ();
  private void Initview () {TV = (TextView) Findviewbyid (r.id.tv);
  LV = (ListView) Findviewbyid (r.id.lv);
  NV = (Navview) Findviewbyid (R.ID.NV);
 Nv.settextview (TV);
  private void InitData () {//initialization data list = new arraylist<> (); for (int i = 0; i < name.length i++) {list.add (new User (name[i), Characterutils.getFirstspell (Name[i]). toUpperCase ()));  //Pinyin sort collections.sort (list, new comparator<user> () {@Override public int compare (user lhs, user RHS)
   {return Lhs.getfirstcharacter (). CompareTo (Rhs.getfirstcharacter ());
  }
  });
  Fill ListView adapter = new Useradapter (this, list);
 Lv.setadapter (adapter);
 }}</user></user>

ListView Child Layout:

<!--? XML version= "1.0" encoding= "Utf-8"?-->
<linearlayout android:background= "#ffffff" android:layout _height= "Match_parent" android:layout_width= "match_parent" android:orientation= "vertical" xmlns:android= "http://" Schemas.android.com/apk/res/android ">
  <textview android:background=" #DBDBDA "android:id=" @+id/tv_ Firstcharacter "android:layout_height=" wrap_content "android:layout_width=" match_parent "android:padding=" 8DP " android:text= "A" android:textcolor= "#000000" android:textsize= "14DP" > 
 <textview android:background= "# FFFFFF "android:id=" @+id/tv_name "android:layout_height=" wrap_content "android:layout_width=" Match_parent "Android :p adding= "8DP" android:text= "Zhang Pillars" android:textcolor= "#2196F3" android:textsize= "14DP" > 
</textview> </textview></linearlayout>

Adapter:

public class Useradapter extends Baseadapter {private list<user> List;
 private user user;
 Private Layoutinflater Minflater;
 private context;
  Public Useradapter (Context context, list<user> list) {this.list = list;
  Minflater = Layoutinflater.from (context);
 This.context = context;
 @Override public int GetCount () {return list.size ();
 @Override public Object getitem (int position) {return list.get (position);
 @Override public long getitemid (int position) {return position; @Override public View getview (int position, View Convertview, ViewGroup parent) {if (Convertview = null) {CONV
  Ertview = minflater.inflate (R.layout.adapter_user, NULL);
  } Viewholder holder = Getviewholder (Convertview);
  user = List.get (position);
   if (position = = 0) {//First data to display letters and names holder.tv_firstCharacter.setVisibility (view.visible);
   Holder.tv_firstCharacter.setText (User.getfirstcharacter ()); Holder.tv_name.setText (User.getusername ());
  else {//other data is judged to be the same letter, where the ASCII code is used to compare the size if (characterutils.getcnascii list.get (position-1). Getfirstcharacter (). CharAt (0)) < Characterutils.getcnascii (User.getfirstcharacter (). CharAt (0))) {//back letter value greater than previous letter value, need to display letter hold
    Er.tv_firstCharacter.setVisibility (view.visible);
    Holder.tv_firstCharacter.setText (User.getfirstcharacter ());
   Holder.tv_name.setText (User.getusername ());
    The value of the else {//back letter is equal to the value of the preceding letter and does not display the letter holder.tv_firstCharacter.setVisibility (View.gone);
   Holder.tv_name.setText (User.getusername ());
 } return Convertview; /** * Get control Management Object * * @param view * @return/private Viewholder Getviewholder (view view) {Viewholder Holde
  R = (viewholder) view.gettag ();
   if (Holder = = NULL) {holder = new Viewholder (view);
  View.settag (holder);
 return holder;
 
  /** * Control Management class * * Private class Viewholder {private TextView tv_firstcharacter, Tv_name; Viewholder (view view) {Tv_firstcharacter = (TextView) vIew.findviewbyid (R.id.tv_firstcharacter);
  Tv_name = (TextView) View.findviewbyid (r.id.tv_name); }/** * Find position by character * * @param s * @return/public int getselectposition (String s) {for (int i = 0; I & Lt GetCount ();
   i++) {String Firchar = List.get (i). Getfirstcharacter ();
   if (Firchar.equals (s)) {return i;
 }} return-1;
 }}</user></user>

Step three: The letter navigation bar slide Event processing, the letter navigation bar and the middle letter linkage

Thinking Analysis:

1. Rewrite the dispatchtouchevent handle sliding event in custom view, and return true at the end.

2, in the main activity passed in a textview, when we slide the text set, when the release of the text disappeared. When you set text, you need to compute the position of text, and if you slip too much, you'll get the array out of bounds, so we're dealing with array bounds inside.

3. Finally, provide an interface to record the letters we slip into, in order to be able to listview linkage with the back.

@Override public boolean dispatchtouchevent (Motionevent event) {//Compute the selected letter int index = (int) (Event.gety ()/GetHeight ()
 * s.length);
 Prevent foot marks from crossing if (index >= s.length) {index = s.length-1;
 else if (Index < 0) {index = 0; Switch (event.getaction ()) {case MotionEvent.ACTION_DOWN:case MotionEvent.ACTION_MOVE:setBackgroundColor (Colo
   R.gray);
   Selected Letters Highlight Choose = Index;
   Intermediate text appears tv.setvisibility (VISIBLE);
   Tv.settext (S[choose]);
   Call the ListView Connector if (listener!= null) {Listener.touchcharacterlistener (s[choose));
   //Redraw invalidate ();
  Break
   Default:setbackgroundcolor (color.transparent);
   Uncheck the letter Highlight choose =-1;
   Hide Middle Text tv.setvisibility (GONE);
   Redraw invalidate ();
 Break
return true;
public Ontouchcharacterlistener Listener; 
public interface Ontouchcharacterlistener {void Touchcharacterlistener (String s);} public void Setlistener (Ontouchcharacterlistener listener) {This.listener = listener;} 
/** * passed in a TextView * * @param TV/public void Settextview (TextView TV) {this.tv = TV;}
 

Step four: Linkage between the letter navigation bar and the ListView

Thinking Analysis:

1, we have passed through the interface to pass a choice of letters, and in the adapter written in accordance with the letter query position method, this time as long as the main activity on the custom view settings listening, Judge can.

ListView Connector
Nv.setlistener (new Navview.ontouchcharacterlistener () {@Override public
 void Touchcharacterlistener (String s) {
  int position = Adapter.getselectposition (s);
  if (position!=-1) {
   lv.setselection (position);
  }}}
);

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.