Android Custom View implements code _android for the letter navigation bar

Source: Internet
Author: User
Tags drawtext

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 xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <edittext android:layout_width= "match_parent" android:layout_height= "Wrap_content" @ Drawable/search_border "android:drawableleft=" @android:d rawable/ic_menu_search "android:padding=" 8DP "/> < Relativelayout android:layout_width= "match_parent" android:layout_height= "Match_parent" > <ListView android: Id= "@+id/lv" android:layout_width= "match_parent" android:layout_height= "match_parent" android:divider= "@null" > <textview android:id= "@+id/tv" android:layout_width= "50DP" android:layout_height= "50DP" Android:layout_ Centerinparent= "true" android:background= "#888888" android:gravity= "center" android:textcolor= "#000000" Android: Textsize= "18DP" android:visibility= "Gone"/> <com.handsome.tulin.view. Navview android:id= "@+id/nv" android:layout_width= "20DP" android:layout_height= "Match_parent" Android:layout_ Alignparentright= "true" android:layout_margin= "16DP"/> </RelativeLayout> </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", "Xia Yu", "Baojian", "Lu Yi", "Choshenyu", "Gije", "Guo", "Huddivan", "Huan Zi", "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" 
"," "Bai-Xu", "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) {RE 
Turn Lhs.getfirstcharacter (). CompareTo (Rhs.getfirstcharacter ()); 
} 
}); 
Fill ListView adapter = new Useradapter (this, list); 
Lv.setadapter (adapter); } 
}

ListView Child Layout:

<?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= "#ffffff" 
android:orientation= "vertical" > 
<textview 
android:id= "@+id/tv_" Firstcharacter " 
android:layout_width=" match_parent " 
android:layout_height=" Wrap_content " 
Android : background= "#DBDBDA" 
android:padding= "8DP" 
android:text= "A" 
android:textcolor= "#000000" 
Android:textsize= "14DP"/> 
<textview 
android:id= "@+id/tv_name" 
match _parent " 
android:layout_height=" wrap_content " 
android:background=" #ffffff " 
android:padding=" 8DP " 
android:text=" 
android:textcolor= "#2196F3" 
android:textsize= "14DP"/> 
</ 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) {Convert 
View = 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 beNo is 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))) {//The value of the back letter is greater than the value of the preceding letter, the letter needs to be displayed holder.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 holder = (V 
Iewholder) 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 < getc Ount (); 
i++) {String Firchar = List.get (i). Getfirstcharacter (); 
if (Firchar.equals (s)) {return i; 
}} return-1; } 
}

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) {//calculates 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 (color.gr 
AY); 
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 a small set to introduce the Android custom view to achieve the code of the letter navigation bar, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.