Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義控件實戰(四):打造通訊錄字母快速索引欄 QuickIndexBar

編輯:關於 Android 程式設計

自定義View通訊錄字母快速索引


在 Android 日常開發中,我們經常在聯繫人界面看到側邊的字母導航欄。當用戶點擊某個字母時,列表會依據漢字的首字母拼音快速定位到對應的 item。這種交互幾乎所有涉及通訊的應用都會用到,無論是 QQ、微信還是微博。今天,我們就一起動手實現這樣一個自定義控件。

先看效果

效果圖如下:

源碼下載地址:https://github.com/gdutxiaoxu/QuickIndex.git

整體思路

源碼其實並不長,加上註釋總共才 180 多行。整體思路可以拆分成幾個步驟:定義 A-Z 字母數組、初始化畫筆、在 onSizeChanged 中獲取控件尺寸、在 onDraw 中繪製字母,最後通過 onTouchEvent 處理觸摸事件並以接口回調的形式把選中字母拋給外部。

首先是類的定義與成員聲明:

 /** * 博客地址:https://blog.csdn.net/gdutxiaoxu * 快速索引,根據字母的索引查找相應的聯系人 * * @author xujun * @time 2015/11/1 21:40. */ public class QuickIndexBar extends View { private static final String[] LETTERS = 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"}; private static final String TAG = "xujun"; private Paint mPaint; //字母的寬度 private int cellWidth; //字母的高度 private float cellHeight; //記錄上一次觸摸的Index private int mLastTouchIndex = -1; //字母被選中顯示的顏色 private int mSelectColor = Color.GRAY; //字母正常顯示的顏色 private int mNormalColor = Color.WHITE; private Context mContext; /** * 暴露一個字母的監聽 */ public interface OnLetterUpdateListener { void onLetterUpdate(String letter); } private OnLetterUpdateListener listener; public OnLetterUpdateListener getListener() { return listener; } /** * 設置字母更新監聽 * * @param listener */ public void setListener(OnLetterUpdateListener listener) { this.listener = listener; } }

構造方法中初始化畫筆

在構造方法裡初始化畫筆,同時為了使用方便,我們封裝了自定義屬性,允許外部自定義選中色與常態色:

 public QuickIndexBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; //初始化自定義屬性 obtainAttrs(attrs); // 初始化畫筆 mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); float textSize = UIUtils.dip2px(15, mContext); mPaint.setTextSize(textSize); mPaint.setTypeface(Typeface.DEFAULT_BOLD); } private void obtainAttrs(AttributeSet attrs) { TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.QuickIndexBar); int selectColor = typedArray.getColor(R.styleable.QuickIndexBar_select_color, -1); if (selectColor != -1) { mSelectColor = selectColor; } int normalColor = typedArray.getColor(R.styleable.QuickIndexBar_normal_color, -1); if (normalColor != -1) { mNormalColor = normalColor; } typedArray.recycle(); }

在 onSizeChanged 中獲取尺寸

接著我們在 onSizeChanged 方法裡拿到控件的寬度和高度。有人可能會問,為什麼不在 onMeasure 裡獲取?其實在 onMeasure 中獲取也可以,只是還需要主動調用一次 measure 方法;而在 onSizeChanged 中,我們直接調用 getMeasuredWidth() 即可拿到寬高,使用起來更為便捷。這裡更重要的是讓大家了解 View 存在這個回調方法以及它的用法。

順便看一下官方對 onSizeChanged 的解釋:

This is called during layout when the size of this view has changed. If you were just added to the view hierarchy, you're called with the old values of 0.

從官方解釋可知,該方法在 onLayout 過程中、當尺寸發生變化時被調用。由於 onMeasure 先於 onLayout 執行,因此此處直接調用 getMeasuredWidth() 是能拿到正確寬度的。

 @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // 獲取單元格的寬和高 cellWidth = getMeasuredWidth(); int mHeight = getMeasuredHeight(); cellHeight = mHeight * 1.0f / LETTERS.length; }

重寫 onDraw 繪製 26 個字母

重寫 onDraw 方法,在其中遍歷並繪製出 26 個字母,根據當前是否被按壓來切換畫筆顏色:

 @Override protected void onDraw(Canvas canvas) { for (int i = 0; i < LETTERS.length; i++) { String text = LETTERS[i]; // 計算坐標 int x = (int) (cellWidth / 2.0f - mPaint.measureText(text) / 2.0f); // 獲取文本的高度 Rect bounds = new Rect();// 矩形 mPaint.getTextBounds(text, 0, text.length(), bounds); int textHeight = bounds.height(); int y = (int) (cellHeight / 2.0f + textHeight / 2.0f + i * cellHeight); // 根據按下的字母, 設置畫筆顏色 mPaint.setColor(mLastTouchIndex == i ? mSelectColor : mNormalColor); // 繪制文本A-Z canvas.drawText(text, x, y, mPaint); } }

處理觸摸事件並回調

講到這裡,工作已完成一大半。接著重寫 onTouchEvent 處理按下或滑動到某個字母的情況。這裡 return true 是為了保證 ACTION_DOWN 之後的 ACTION_MOVE 等後續事件能夠被順利接收,這涉及到 View 的事件分發機制。同時我們記錄下當前觸摸的是哪一個字母:

 @Override public boolean onTouchEvent(MotionEvent event) { int index = -1; switch (MotionEventCompat.getActionMasked(event)) { case MotionEvent.ACTION_DOWN: // 獲取當前觸摸到的字母索引 index = (int) (event.getY() / cellHeight); if (index >= 0 && index < LETTERS.length) { // 判斷是否跟上一次觸摸到的一樣,不一樣才進行回調 if (index != mLastTouchIndex) { if (listener != null) { listener.onLetterUpdate(LETTERS[index]); } Log.d(TAG, "onTouchEvent: " + LETTERS[index]); //記錄上一次觸摸的Index為當前的index; mLastTouchIndex = index; } } break; case MotionEvent.ACTION_MOVE: index = (int) (event.getY() / cellHeight); if (index >= 0 && index < LETTERS.length) { if (index != mLastTouchIndex) { if (listener != null) { listener.onLetterUpdate(LETTERS[index]); } Log.d(TAG, "onTouchEvent: " + LETTERS[index]); mLastTouchIndex = index; } } break; case MotionEvent.ACTION_UP: // 手指抬起的時候重置 mLastTouchIndex = -1; break; default: break; } //調用這個方法會重新調用draw方法,重新繪制 invalidate(); return true; }

知道了當前觸摸的是哪個字母後,如何把這些信息暴露給外界呢?很自然想到用接口回調。為此我們提供了 OnLetterUpdateListener 接口與 setListener 方法,這樣就成功地把按下的字母信息傳遞給了外部使用方。

與 ListView 結合使用

下面貼出結合 ListView 的核心代碼,想深入了解的讀者可以點擊源碼下載地址獲取完整實現。思路解析如下:

1. 在 List 數據中查找首字母為當前觸摸字母的項,若存在則返回相應的 index;
2. 然後調用 ListView 的 setSelection(i) 方法選中該 Item。

 mQuickIndexBar.setListener(new OnLetterUpdateListener() { @Override public void onLetterUpdate(String letter) { // UIUtils.showToast(getApplicationContext(), letter); showLetter(letter); // 根據字母定位ListView, 找到集合中第一個以letter為拼音首字母的對象,得到索引 for (int i = 0; i < persons.size(); i++) { Person person = persons.get(i); String l = person.getPinyin().charAt(0) + ""; if (TextUtils.equals(letter, l)) { // 匹配成功 mListView.setSelection(i); break; } } } });

至於列表中有些 item 顯示字母、有些則不顯示,其實就是判斷上一個 item 的首字母是否與當前首字母相同:不同才顯示當前字母。需要注意的是,當 position 等於 0 時要做特殊處理,代碼如下:

 String str = null; String currentLetter = p.getPinyin().charAt(0) + ""; // 根據上一個首字母,決定當前是否顯示字母 if(position == 0){ str = currentLetter; }else { // 上一個人的拼音的首字母 String preLetter = persons.get(position - 1).getPinyin().charAt(0) + ""; if(!TextUtils.equals(preLetter, currentLetter)){ str = currentLetter; } } // 根據str是否為空,決定是否顯示索引欄 mViewHolder.mIndex.setVisibility(str == null ? View.GONE : View.VISIBLE);

小結

至此,QuickIndexBar 的分析就告一段落。這個控件把 Canvas 繪製、觸摸事件處理與接口回調有機結合,是一個很好的自定義 View 練習案例。

源碼下載地址:https://github.com/gdutxiaoxu/QuickIndex.git

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved