当前位置: 代码迷 >> Android >> android ListView依据字母排序和定位
  详细解决方案

android ListView依据字母排序和定位

热度:32   发布时间:2016-05-01 13:32:16.0
android ListView根据字母排序和定位

基本上很多应用都是用了这个功能当数据多时方便快速查看浏览定位查询等,本案例功能比较简单,需要跟完善的话就要继续优化。

先上运行效果图如下:

?


?

?

第一步:首相自定义SideBar类继承View类,用于绘制A-Z文字控件,如下:

?

Java代码 复制代码?收藏代码
  1. import?android.content.Context; ??
  2. import?android.graphics.Bitmap; ??
  3. import?android.graphics.BitmapFactory; ??
  4. import?android.graphics.Canvas; ??
  5. import?android.graphics.Paint; ??
  6. import?android.graphics.Paint.Style; ??
  7. import?android.graphics.drawable.ColorDrawable; ??
  8. import?android.util.AttributeSet; ??
  9. import?android.view.MotionEvent; ??
  10. import?android.view.View; ??
  11. import?android.widget.HeaderViewListAdapter; ??
  12. import?android.widget.ListView; ??
  13. import?android.widget.SectionIndexer; ??
  14. import?android.widget.TextView; ??
  15. ??
  16. public?class?SideBar?extends?View?{ ??
  17. ????private?char[]?l; ??
  18. ????private?SectionIndexer?sectionIndexter?=?null; ??
  19. ????private?ListView?list; ??
  20. ????private?TextView?mDialogText; ??
  21. ????Bitmap?mbitmap; ??
  22. ????private?int?type?=?1; ??
  23. ????private?int?color?=?0xff858c94; ??
  24. ??
  25. ????public?SideBar(Context?context)?{ ??
  26. ????????super(context); ??
  27. ????????init(); ??
  28. ????} ??
  29. ??
  30. ????public?SideBar(Context?context,?AttributeSet?attrs)?{ ??
  31. ????????super(context,?attrs); ??
  32. ????????init(); ??
  33. ????} ??
  34. ??
  35. ????private?void?init()?{ ??
  36. ??
  37. ????????l?=?new?char[]?{?'!','A',?'B',?'C',?'D',?'E',?'F',?'G',?'H', ??
  38. ?????????'I',?'J',?'K',?'L',?'M',?'N',?'O',?'P',?'Q',?'R',?'S',?'T',?'U',?'V', ??
  39. ??????????'W',?'X',?'Y',?'Z','#'}; ??
  40. ????????mbitmap?=?BitmapFactory.decodeResource(getResources(), ??
  41. ????????????????R.drawable.scroll_bar_search_icon); ??
  42. ????} ??
  43. ??
  44. ????public?SideBar(Context?context,?AttributeSet?attrs,?int?defStyle)?{ ??
  45. ????????super(context,?attrs,?defStyle); ??
  46. ????????init(); ??
  47. ????} ??
  48. ??
  49. ??
  50. ????public?void?setListView(ListView?_list)?{ ??
  51. ????????list?=?_list; ??
  52. ????????HeaderViewListAdapter?ha?=?(HeaderViewListAdapter)?_list ??
  53. ????????????????.getAdapter(); ??
  54. ????????MyAdapter?ad?=?(MyAdapter)ha.getWrappedAdapter(); ??
  55. ????????sectionIndexter?=?(SectionIndexer)?ad; ??
  56. ???????? ??
  57. ????} ??
  58. ??
  59. ????public?void?setTextView(TextView?mDialogText)?{ ??
  60. ????????this.mDialogText?=?mDialogText; ??
  61. ????} ??
  62. ??
  63. ????public?boolean?onTouchEvent(MotionEvent?event)?{ ??
  64. ??
  65. ????????super.onTouchEvent(event); ??
  66. ????????int?i?=?(int)?event.getY(); ??
  67. ??
  68. ????????int?idx?=?i?/?(getMeasuredHeight()?/?l.length); ??
  69. ????????if?(idx?>=?l.length)?{ ??
  70. ????????????idx?=?l.length?-?1; ??
  71. ????????}?else?if?(idx?<?0)?{ ??
  72. ????????????idx?=?0; ??
  73. ????????} ??
  74. ????????if?(event.getAction()?==?MotionEvent.ACTION_DOWN ??
  75. ????????????????||?event.getAction()?==?MotionEvent.ACTION_MOVE)?{ ??
  76. ????????????setBackgroundResource(R.drawable.scrollbar_bg); ??
  77. ????????????mDialogText.setVisibility(View.VISIBLE); ??
  78. ????????????if?(idx?==?0)?{ ??
  79. ????????????????mDialogText.setText("Search"); ??
  80. ????????????????mDialogText.setTextSize(16); ??
  81. ????????????}?else?{ ??
  82. ????????????????mDialogText.setText(String.valueOf(l[idx])); ??
  83. ????????????????mDialogText.setTextSize(34); ??
  84. ????????????} ??
  85. ????????????if?(sectionIndexter?==?null)?{ ??
  86. ??
  87. ???????????? ??
  88. ??
  89. ????????????????sectionIndexter?=?(SectionIndexer)?list.getAdapter(); ??
  90. ???????????????? ??
  91. ????????????} ??
  92. ????????????int?position?=?sectionIndexter.getPositionForSection(l[idx]); ??
  93. ??
  94. ????????????if?(position?==?-1)?{ ??
  95. ????????????????return?true; ??
  96. ????????????} ??
  97. ????????????list.setSelection(position); ??
  98. ????????}?else?{ ??
  99. ????????????mDialogText.setVisibility(View.INVISIBLE); ??
  100. ??
  101. ????????} ??
  102. ????????if?(event.getAction()?==?MotionEvent.ACTION_UP)?{ ??
  103. ????????????setBackgroundDrawable(new?ColorDrawable(0x00000000)); ??
  104. ????????} ??
  105. ????????return?true; ??
  106. ????} ??
  107. ??
  108. ????protected?void?onDraw(Canvas?canvas)?{ ??
  109. ????????Paint?paint?=?new?Paint(); ??
  110. ????????paint.setColor(color); ??
  111. ????????paint.setTextSize(12); ??
  112. ????????paint.setStyle(Style.FILL);????? ??
  113. ????????paint.setTextAlign(Paint.Align.CENTER); ??
  114. ????????float?widthCenter?=?getMeasuredWidth()?/?2; ??
  115. ????????if?(l.length?>?0)?{ ??
  116. ????????????float?height?=?getMeasuredHeight()?/?l.length; ??
  117. ????????????for?(int?i?=?0;?i?<?l.length;?i++)?{ ??
  118. ????????????????if?(i?==?0?&&?type?!=?2)?{ ??
  119. ????????????????????canvas.drawBitmap(mbitmap,?widthCenter?-?7,?(i?+?1) ??
  120. ????????????????????????????*?height?-?height?/?2,?paint); ??
  121. ????????????????}?else??
  122. ????????????????????canvas.drawText(String.valueOf(l[i]),?widthCenter, ??
  123. ????????????????????????????(i?+?1)?*?height,?paint); ??
  124. ????????????} ??
  125. ????????} ??
  126. ????????this.invalidate(); ??
  127. ????????super.onDraw(canvas); ??
  128. ????} ??
  129. }??
import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Paint;import android.graphics.Paint.Style;import android.graphics.drawable.ColorDrawable;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.widget.HeaderViewListAdapter;import android.widget.ListView;import android.widget.SectionIndexer;import android.widget.TextView;public class SideBar extends View {	private char[] l;	private SectionIndexer sectionIndexter = null;	private ListView list;	private TextView mDialogText;	Bitmap mbitmap;	private int type = 1;	private int color = 0xff858c94;	public SideBar(Context context) {		super(context);		init();	}	public SideBar(Context context, AttributeSet attrs) {		super(context, attrs);		init();	}	private void init() {		l = new char[] { '!','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','#'};		mbitmap = BitmapFactory.decodeResource(getResources(),				R.drawable.scroll_bar_search_icon);	}	public SideBar(Context context, AttributeSet attrs, int defStyle) {		super(context, attrs, defStyle);		init();	}	public void setListView(ListView _list) {		list = _list;		HeaderViewListAdapter ha = (HeaderViewListAdapter) _list				.getAdapter();		MyAdapter ad = (MyAdapter)ha.getWrappedAdapter();		sectionIndexter = (SectionIndexer) ad;			}	public void setTextView(TextView mDialogText) {		this.mDialogText = mDialogText;	}	public boolean onTouchEvent(MotionEvent event) {		super.onTouchEvent(event);		int i = (int) event.getY();		int idx = i / (getMeasuredHeight() / l.length);		if (idx >= l.length) {			idx = l.length - 1;		} else if (idx < 0) {			idx = 0;		}		if (event.getAction() == MotionEvent.ACTION_DOWN				|| event.getAction() == MotionEvent.ACTION_MOVE) {			setBackgroundResource(R.drawable.scrollbar_bg);			mDialogText.setVisibility(View.VISIBLE);			if (idx == 0) {				mDialogText.setText("Search");				mDialogText.setTextSize(16);			} else {				mDialogText.setText(String.valueOf(l[idx]));				mDialogText.setTextSize(34);			}			if (sectionIndexter == null) {							sectionIndexter = (SectionIndexer) list.getAdapter();							}			int position = sectionIndexter.getPositionForSection(l[idx]);			if (position == -1) {				return true;			}			list.setSelection(position);		} else {			mDialogText.setVisibility(View.INVISIBLE);		}		if (event.getAction() == MotionEvent.ACTION_UP) {			setBackgroundDrawable(new ColorDrawable(0x00000000));		}		return true;	}	protected void onDraw(Canvas canvas) {		Paint paint = new Paint();		paint.setColor(color);		paint.setTextSize(12);		paint.setStyle(Style.FILL);				paint.setTextAlign(Paint.Align.CENTER);		float widthCenter = getMeasuredWidth() / 2;		if (l.length > 0) {			float height = getMeasuredHeight() / l.length;			for (int i = 0; i < l.length; i++) {				if (i == 0 && type != 2) {					canvas.drawBitmap(mbitmap, widthCenter - 7, (i + 1)							* height - height / 2, paint);				} else					canvas.drawText(String.valueOf(l[i]), widthCenter,							(i + 1) * height, paint);			}		}		this.invalidate();		super.onDraw(canvas);	}}

?

?

第二步:设计xml:

?

Xml代码 复制代码?收藏代码
  1. <FrameLayout?xmlns:android="http://schemas.android.com/apk/res/android"??
  2. ????xmlns:tools="http://schemas.android.com/tools"??
  3. ????android:layout_width="match_parent"??
  4. ????android:layout_height="match_parent"?>??
  5. ??
  6. ????<ListView??
  7. ????????android:id="@+id/list"??
  8. ????????android:layout_width="fill_parent"??
  9. ????????android:layout_height="fill_parent"??
  10. ????????android:divider="@null"?/>??
  11. ??
  12. ????<com.example.listsildedel.SideBar??
  13. ????????android:id="@+id/sideBar"??
  14. ????????android:layout_width="25dp"??
  15. ????????android:layout_height="wrap_content"??
  16. ????????android:layout_gravity="right|center_vertical"?/>??
  17. ??
  18. </FrameLayout>??
<FrameLayout 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" >    <ListView        android:id="@+id/list"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:divider="@null" />    <com.example.listsildedel.SideBar        android:id="@+id/sideBar"        android:layout_width="25dp"        android:layout_height="wrap_content"        android:layout_gravity="right|center_vertical" /></FrameLayout>

?

第三步:创建MyAdapter继承BaseAdapter并实现SectionIndexer接口注意这里一定要实现这个接口以便实现对应a-z的选择定位功能:

?

Java代码 复制代码?收藏代码
  1. import?java.util.List; ??
  2. ??
  3. import?android.content.Context; ??
  4. import?android.view.LayoutInflater; ??
  5. import?android.view.View; ??
  6. import?android.view.ViewGroup; ??
  7. import?android.widget.BaseAdapter; ??
  8. import?android.widget.SectionIndexer; ??
  9. import?android.widget.TextView; ??
  10. ??
  11. public?class?MyAdapter?extends?BaseAdapter?implements?SectionIndexer{ ??
  12. ??
  13. ????private?List<Content>?list?=?null; ??
  14. ????private?Context?mContext; ??
  15. ????private?SectionIndexer?mIndexer; ??
  16. ???? ??
  17. ????public?MyAdapter(Context?mContext,?List<Content>?list)?{ ??
  18. ????????this.mContext?=?mContext; ??
  19. ????????this.list?=?list; ??
  20. ??
  21. ????} ??
  22. ??
  23. ????public?int?getCount()?{ ??
  24. ????????return?this.list.size(); ??
  25. ????} ??
  26. ??
  27. ????public?Object?getItem(int?position)?{ ??
  28. ????????return?null; ??
  29. ????} ??
  30. ??
  31. ????public?long?getItemId(int?position)?{ ??
  32. ????????return?position; ??
  33. ????} ??
  34. ??
  35. ????public?View?getView(final?int?position,?View?view,?ViewGroup?arg2)?{ ??
  36. ????????ViewHolder?viewHolder?=?null; ??
  37. ????????if?(view?==?null)?{ ??
  38. ????????????viewHolder?=?new?ViewHolder(); ??
  39. ????????????view?=?LayoutInflater.from(mContext).inflate(R.layout.item,?null); ??
  40. ????????????viewHolder.tvTitle?=?(TextView)?view.findViewById(R.id.title); ??
  41. ????????????viewHolder.tvLetter?=?(TextView)?view.findViewById(R.id.catalog); ??
  42. ????????????view.setTag(viewHolder); ??
  43. ????????}?else?{ ??
  44. ????????????viewHolder?=?(ViewHolder)?view.getTag(); ??
  45. ????????} ??
  46. ????????final?Content?mContent?=?list.get(position); ??
  47. ????????if?(position?==?0)?{ ??
  48. ????????????viewHolder.tvLetter.setVisibility(View.VISIBLE); ??
  49. ????????????viewHolder.tvLetter.setText(mContent.getLetter()); ??
  50. ????????}?else?{ ??
  51. ????????????String?lastCatalog?=?list.get(position?-?1).getLetter(); ??
  52. ????????????if?(mContent.getLetter().equals(lastCatalog))?{ ??
  53. ????????????????viewHolder.tvLetter.setVisibility(View.GONE); ??
  54. ????????????}?else?{ ??
  55. ????????????????viewHolder.tvLetter.setVisibility(View.VISIBLE); ??
  56. ????????????????viewHolder.tvLetter.setText(mContent.getLetter()); ??
  57. ????????????} ??
  58. ????????} ??
  59. ???? ??
  60. ????????viewHolder.tvTitle.setText(this.list.get(position).getName()); ??
  61. ???????? ??
  62. ????????return?view; ??
  63. ??
  64. ????} ??
  65. ???? ??
  66. ??
  67. ??
  68. ????final?static?class?ViewHolder?{ ??
  69. ????????TextView?tvTitle; ??
  70. ????????TextView?tvLetter; ??
  71. ????} ??
  72. ??
  73. ??
  74. ????public?Object[]?getSections()?{ ??
  75. ????????//?TODO?Auto-generated?method?stub ??
  76. ????????return?null; ??
  77. ????} ??
  78. ??
  79. ????public?int?getSectionForPosition(int?position)?{ ??
  80. ???????? ??
  81. ????????return?0; ??
  82. ????} ??
  83. ??
  84. ????public?int?getPositionForSection(int?section)?{ ??
  85. ????????Content?mContent; ??
  86. ????????String?l; ??
  87. ????????if?(section?==?'!')?{ ??
  88. ????????????return?0; ??
  89. ????????}?else?{ ??
  90. ????????????for?(int?i?=?0;?i?<?getCount();?i++)?{ ??
  91. ????????????????mContent?=?(Content)?list.get(i); ??
  92. ????????????????l?=?mContent.getLetter(); ??
  93. ????????????????char?firstChar?=?l.toUpperCase().charAt(0); ??
  94. ????????????????if?(firstChar?==?section)?{ ??
  95. ????????????????????return?i?+?1; ??
  96. ????????????????} ??
  97. ??
  98. ????????????} ??
  99. ????????} ??
  100. ????????mContent?=?null; ??
  101. ????????l?=?null; ??
  102. ????????return?-1; ??
  103. ????} ??
  104. }??
import java.util.List;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.SectionIndexer;import android.widget.TextView;public class MyAdapter extends BaseAdapter implements SectionIndexer{	private List<Content> list = null;	private Context mContext;	private SectionIndexer mIndexer;		public MyAdapter(Context mContext, List<Content> list) {		this.mContext = mContext;		this.list = list;	}	public int getCount() {		return this.list.size();	}	public Object getItem(int position) {		return null;	}	public long getItemId(int position) {		return position;	}	public View getView(final int position, View view, ViewGroup arg2) {		ViewHolder viewHolder = null;		if (view == null) {			viewHolder = new ViewHolder();			view = LayoutInflater.from(mContext).inflate(R.layout.item, null);			viewHolder.tvTitle = (TextView) view.findViewById(R.id.title);			viewHolder.tvLetter = (TextView) view.findViewById(R.id.catalog);			view.setTag(viewHolder);		} else {			viewHolder = (ViewHolder) view.getTag();		}		final Content mContent = list.get(position);		if (position == 0) {			viewHolder.tvLetter.setVisibility(View.VISIBLE);			viewHolder.tvLetter.setText(mContent.getLetter());		} else {			String lastCatalog = list.get(position - 1).getLetter();			if (mContent.getLetter().equals(lastCatalog)) {				viewHolder.tvLetter.setVisibility(View.GONE);			} else {				viewHolder.tvLetter.setVisibility(View.VISIBLE);				viewHolder.tvLetter.setText(mContent.getLetter());			}		}			viewHolder.tvTitle.setText(this.list.get(position).getName());				return view;	}		final static class ViewHolder {		TextView tvTitle;		TextView tvLetter;	}	public Object[] getSections() {		// TODO Auto-generated method stub		return null;	}	public int getSectionForPosition(int position) {				return 0;	}	public int getPositionForSection(int section) {		Content mContent;		String l;		if (section == '!') {			return 0;		} else {			for (int i = 0; i < getCount(); i++) {				mContent = (Content) list.get(i);				l = mContent.getLetter();				char firstChar = l.toUpperCase().charAt(0);				if (firstChar == section) {					return i + 1;				}			}		}		mContent = null;		l = null;		return -1;	}}

?第四步:编写MainActivity类

?

Java代码 复制代码?收藏代码
  1. import?java.util.ArrayList; ??
  2. import?java.util.Collections; ??
  3. import?java.util.List; ??
  4. ??
  5. import?android.app.Activity; ??
  6. import?android.content.Context; ??
  7. import?android.graphics.PixelFormat; ??
  8. import?android.os.Bundle; ??
  9. import?android.view.LayoutInflater; ??
  10. import?android.view.View; ??
  11. import?android.view.WindowManager; ??
  12. import?android.widget.LinearLayout.LayoutParams; ??
  13. import?android.widget.ListView; ??
  14. import?android.widget.TextView; ??
  15. ??
  16. public?class?MainActivity?extends?Activity?{ ??
  17. ??
  18. ????private?ListView?mListView; ??
  19. ????private?SideBar?indexBar; ??
  20. ????private?WindowManager?mWindowManager; ??
  21. ????private?TextView?mDialogText; ??
  22. ????private?View?head; ??
  23. ??
  24. ????@Override??
  25. ????public?void?onCreate(Bundle?savedInstanceState)?{ ??
  26. ?????????//启动activity时不自动弹出软键盘 ??
  27. ????????getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);? ??
  28. ????????super.onCreate(savedInstanceState); ??
  29. ????????setContentView(R.layout.activity_main); ??
  30. ????????mListView?=?(ListView)?this.findViewById(R.id.list); ??
  31. ????????indexBar?=?(SideBar)?findViewById(R.id.sideBar); ??
  32. ????????mDialogText?=?(TextView)?LayoutInflater.from(this).inflate(R.layout.list_position,?null); ??
  33. ????????head?=?LayoutInflater.from(this).inflate(R.layout.head,?null); ??
  34. ????????mListView.addHeaderView(head); ??
  35. ????????mDialogText.setVisibility(View.INVISIBLE); ??
  36. ????????mWindowManager?=?(WindowManager)?getSystemService(Context.WINDOW_SERVICE); ??
  37. ????????WindowManager.LayoutParams?lp?=?new?WindowManager.LayoutParams( ??
  38. ????????????????LayoutParams.WRAP_CONTENT,?LayoutParams.WRAP_CONTENT, ??
  39. ????????????????WindowManager.LayoutParams.TYPE_APPLICATION, ??
  40. ????????????????WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE ??
  41. ????????????????????????|?WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, ??
  42. ????????????????PixelFormat.TRANSLUCENT); ??
  43. ????????mWindowManager.addView(mDialogText,?lp); ??
  44. ????????indexBar.setTextView(mDialogText); ??
  45. ????????//初始化数据 ??
  46. ????????List<Content>?list?=?new?ArrayList<Content>(); ??
  47. ????????for?(int?i?=?0;?i?<?10;?i++)?{ ??
  48. ????????????Content?m; ??
  49. ????????????if?(i?<?3) ??
  50. ????????????????m?=?new?Content("A",?"选项"?+?i); ??
  51. ????????????else?if?(i?<?6) ??
  52. ????????????????m?=?new?Content("F",?"选项"?+?i); ??
  53. ????????????else??
  54. ????????????????m?=?new?Content("D",?"选项"?+?i); ??
  55. ????????????list.add(m); ??
  56. ????????} ??
  57. ????????//根据a-z进行排序 ??
  58. ????????Collections.sort(list,?new?PinyinComparator()); ??
  59. ????????//?实例化自定义内容适配类?????? ??
  60. ????????MyAdapter?adapter?=?new?MyAdapter(this,?list); ??
  61. ????????//?为listView设置适配 ??
  62. ????????mListView.setAdapter(adapter); ??
  63. ????????//设置SideBar的ListView内容实现点击a-z中任意一个进行定位 ??
  64. ????????indexBar.setListView(mListView);???????? ??
  65. ????} ??
  66. ??
  67. }?
  相关解决方案