1. 程式人生 > 程式設計 >Android自定義字母導航欄

Android自定義字母導航欄

本文例項為大家分享了Android字母導航欄的具體程式碼,供大家參考,具體內容如下

效果

實現邏輯

明確需求

字母導航欄在實際開發中還是比較多見的,城市選擇、名稱選擇等等可能需要到。 現在要做到的就是在滑動控制元件過程中可以有內容以及 下標的回撥,方便處理其他邏輯!

整理思路

1、確定控制元件的尺寸,防止內容顯示不全。相關的邏輯在onMeasure()方法中處理;
2、繪製顯示的內容,在按下和抬起不同狀態下文字、背景的顏色。相關邏輯在onDraw()方法中;
3、滑動事件的處理以及事件回撥。相關邏輯在onTouchEvent()方法中;

動手實現

在需求明確、思路清晰的情況下就要開始動手實現(需要了解自定義View的一些基礎API)。核心程式碼就onDraw()中。在程式碼中有思路和註釋,可以結合程式碼一起看看。如果有疑惑、優化、錯誤的地方請在評論區提出,共同進步!

完整程式碼

/**
 * 自定義字母導航欄
 * 
 * 總的來說就四步
 * 1、測量控制元件尺寸{@link #onMeasure(int,int)}
 * 2、繪製顯示內容(背景以及字元){@link #onDraw(Canvas)}
 * 3、處理滑動事件{@link #onTouchEvent(MotionEvent)}
 * 4、暴露介面{@link #setOnNavigationScrollerListener(OnNavigationScrollerListener)}
 *
 * @attr customTextColorDefault //導航欄預設文字顏色
 * @attr customTextColorDown //導航欄按下文字顏色
 * @attr customBackgroundColorDown //導航欄按下背景顏色
 * @attr customLetterDivHeight //導航欄內容高度間隔
 * @attr customTextSize //導航欄文字尺寸
 * @attr customBackgroundAngle //導航欄背景角度
 */
public class CustomLetterNavigationView extends View {
  private static final String TAG = "CustomLetterNavigation";
  //導航內容
  private String[] mNavigationContent;
  //導航欄內容間隔
  private float mContentDiv;
  //導航欄文字大小
  private float mContentTextSize;
  //導航欄文字顏色
  private int mContentTextColor;
  //導航欄按下時背景顏色
  private int mBackgroundColor;
  //導航欄按下時圓角度數
  private int mBackGroundAngle = 0;
  //導航欄按下時文字顏色
  private int mDownContentTextColor;
  private TextPaint mTextPaint;
  private Paint mPaintBackgrount;
  private boolean mEventActionState = false;
  private String mCurrentLetter = "";
  private OnNavigationScrollerListener mOnNavigationScrollerListener;
  private final RectF mRectF = new RectF();
  public CustomLetterNavigationView(Context context) {
    this(context,null);
  }

  public CustomLetterNavigationView(Context context,@Nullable AttributeSet attrs) {
    this(context,attrs,0);
  }

  public CustomLetterNavigationView(Context context,@Nullable AttributeSet attrs,int defStyleAttr) {
    super(context,defStyleAttr);
    initDefaultData();//初始化預設資料
    initAttrs(context,attrs);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    /**
     * <P>
     *   這裡我們分為兩步
     *
     *   1、繪製背景
     *    這裡簡單,直接呼叫Canvas的drawRoundRect()方法直接繪製
     *   2、繪製顯示文字
     *    繪製文字首先要定位,定位每個字元的座標
     *    X軸簡單,寬度的一半
     *    Y軸座標通過每個字元的高heightShould乘以已繪製字元的數目
     * </P>
     */
    int mViewWidth = getWidth();
    //繪製背景
    mRectF.set(0,mViewWidth,getHeight());
    if (mEventActionState) {
      mTextPaint.setColor(mDownContentTextColor);
      mPaintBackgrount.setColor(mBackgroundColor);
      canvas.drawRoundRect(mRectF,mBackGroundAngle,mPaintBackgrount);
    } else {
      mTextPaint.setColor(mContentTextColor);
      mPaintBackgrount.setColor(Color.TRANSPARENT);
      Drawable mBackground = getBackground();
      if (mBackground instanceof ColorDrawable) {
        mPaintBackgrount.setColor(((ColorDrawable) mBackground).getColor());
      }
      canvas.drawRoundRect(mRectF,mPaintBackgrount);
    }
    //繪製文字
    float textX = mViewWidth / 2;
    //X軸座標
    int contentLenght = getContentLength();
    //Y軸座標(這裡在測量的時候多加入了兩個間隔高度要減去,同時還有Padding值)
    float heightShould = (getHeight() - mContentDiv * 2 - getPaddingTop() - getPaddingBottom()) / contentLenght;
    for (int i = 0; i < contentLenght; i++) {
      //計算Y軸的座標
      float startY = ((i + 1) * heightShould) + getPaddingTop();
      //繪製文字
      canvas.drawText(mNavigationContent[i],textX,startY,mTextPaint);
    }
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    /**
     * 這裡主要處理手指滑動事件
     */
    float mEventY = event.getY();
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        //手指按下的時候,修改Enent狀態、重繪背景、觸發回撥
        mEventActionState = true;
        invalidate();
        if (mOnNavigationScrollerListener != null) {
          mOnNavigationScrollerListener.onDown();
        }
        scrollCount(mEventY);
        break;
      case MotionEvent.ACTION_MOVE:
        scrollCount(mEventY);
        break;
      case MotionEvent.ACTION_CANCEL:
      case MotionEvent.ACTION_UP:
        //手指離開的時候,修改Enent狀態、重繪背景、觸發回撥
        mEventActionState = false;
        invalidate();
        if (mOnNavigationScrollerListener != null) {
          mOnNavigationScrollerListener.onUp();
        }
        break;
    }
    return true;
  }


  @Override
  protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec,heightMeasureSpec);
    /**
     * <p>
     *   這裡做了簡單的適應,其目的就是為了能夠正常的顯示我們的內容
     *
     *   不管設定的是真實尺寸或者是包裹內容,都會以內容的最小尺寸為
     *   基礎,如果設定的控制元件尺寸大於我們內容的最小尺寸,就使用控制元件
     *   尺寸,反之使用內容的最小尺寸!
     * </p>
     */
    int widhtMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    //獲取控制元件的尺寸
    int actualWidth = MeasureSpec.getSize(widthMeasureSpec);
    int actualHeight = MeasureSpec.getSize(heightMeasureSpec);
    int contentLegth = getContentLength();
    //計算一個文字的尺寸
    Rect mRect = measureTextSize();
    //內容的最小寬度
    float contentWidth = mRect.width() + mContentDiv * 2;
    //內容的最小高度
    float contentHeight = mRect.height() * contentLegth + mContentDiv * (contentLegth + 3);
    if (MeasureSpec.AT_MOST == widhtMode) {
      //寬度包裹內容
      actualWidth = (int) contentWidth + getPaddingLeft() + getPaddingRight();
    } else if (MeasureSpec.EXACTLY == widhtMode) {
      //寬度限制
      if (actualWidth < contentWidth) {
        actualWidth = (int) contentWidth + getPaddingLeft() + getPaddingRight();
      }
    }
    if (MeasureSpec.AT_MOST == heightMode) {
      //高度包裹內容
      actualHeight = (int) contentHeight + getPaddingTop() + getPaddingBottom();
    } else if (MeasureSpec.EXACTLY == widhtMode) {
      //高度限制
      if (actualHeight < contentHeight) {
        actualHeight = (int) contentHeight + getPaddingTop() + getPaddingBottom();
      }
    }
    setMeasuredDimension(actualWidth,actualHeight);
  }


  /**
   * 初始化預設資料
   */
  private void initDefaultData() {
    mNavigationContent = 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"};
    mContentDiv = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5,getResources().getDisplayMetrics());
    mContentTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,14,getResources().getDisplayMetrics());
    mContentTextColor = Color.parseColor("#333333");
    mDownContentTextColor = Color.WHITE;
    mBackgroundColor = Color.parseColor("#d7d7d7");
    mBackGroundAngle = 0;
    //繪製文字畫筆
    mTextPaint = new TextPaint();
    mTextPaint.setAntiAlias(true);
    mTextPaint.setTextSize(mContentTextSize);
    mTextPaint.setColor(mContentTextColor);
    mTextPaint.setTextAlign(Paint.Align.CENTER);
    //繪製背景畫筆
    mPaintBackgrount = new Paint();
    mPaintBackgrount.setAntiAlias(true);
    mPaintBackgrount.setStyle(Paint.Style.FILL);
  }

  /**
   * 初始化自定義屬性
   *
   * @param context
   * @param attrs
   */
  private void initAttrs(Context context,AttributeSet attrs) {
    TypedArray mTypedArray = context.obtainStyledAttributes(attrs,R.styleable.CustomLetterNavigationView);
    mContentTextColor = mTypedArray.getColor(R.styleable.CustomLetterNavigationView_customTextColorDefault,mContentTextColor);
    mBackgroundColor = mTypedArray.getColor(R.styleable.CustomLetterNavigationView_customBackgroundColorDown,mBackgroundColor);
    mDownContentTextColor = mTypedArray.getColor(R.styleable.CustomLetterNavigationView_customTextColorDown,mDownContentTextColor);
    mContentTextSize = mTypedArray.getDimension(R.styleable.CustomLetterNavigationView_customTextSize,mContentTextSize);
    mContentDiv = mTypedArray.getFloat(R.styleable.CustomLetterNavigationView_customLetterDivHeight,mContentDiv);
    mBackGroundAngle = mTypedArray.getInt(R.styleable.CustomLetterNavigationView_customBackgroundAngle,mBackGroundAngle);
    mTypedArray.recycle();
  }


  /**
   * 獲取內容長度
   *
   * @return 內容長度
   */
  private int getContentLength() {
    if (mNavigationContent != null) {
      return mNavigationContent.length;
    }
    return 0;
  }

  /**
   * 滑動計算
   *
   * @param mEventY Y軸滑動距離
   */
  private void scrollCount(float mEventY) {
    //滑動的時候利用滑動距離和每一個字元高度進行取整,獲取到Index
    Rect mRect = measureTextSize();
    int index = (int) ((mEventY - getPaddingTop() - getPaddingBottom() - mContentDiv * 2) / (mRect.height() + mContentDiv));
    //防止越界
    if (index >= 0 && index < getContentLength()) {
      String newLetter = mNavigationContent[index];
      //防止重複觸發回撥
      if (!mCurrentLetter.equals(newLetter)) {
        mCurrentLetter = newLetter;
        if (mOnNavigationScrollerListener != null) {
          mOnNavigationScrollerListener.onScroll(mCurrentLetter,index);
        }
      }
    }
  }

  /**
   * 測量文字的尺寸
   *
   * @return 一個漢字的矩陣
   */
  public Rect measureTextSize() {
    Rect mRect = new Rect();
    if (mTextPaint != null) {
      mTextPaint.getTextBounds("田",1,mRect);
    }
    return mRect;
  }


  /**
   * 設定導航欄滑動監聽
   *
   * @param onNavigationScrollerListener
   */
  public void setOnNavigationScrollerListener(OnNavigationScrollerListener onNavigationScrollerListener) {
    this.mOnNavigationScrollerListener = onNavigationScrollerListener;
  }

  /**
   * 設定導航欄顯示內容
   *
   * @param content 需要顯示的內容
   */
  public void setNavigationContent(String content) {
    if (!TextUtils.isEmpty(content)) {
      mNavigationContent = null;
      mNavigationContent = new String[content.length()];
      for (int i = 0; i < content.length(); i++) {
        mNavigationContent[i] = String.valueOf(content.charAt(i));
      }
    }
    //需要重新測量
    requestLayout();
  }

  public interface OnNavigationScrollerListener {
    //按下
    void onDown();

    //滑動
    void onScroll(String letter,int position);

    //離開
    void onUp();

  }
}

自定義屬性

<declare-styleable name="CustomLetterNavigationView">
    <attr name="customTextColorDefault" format="color" />
    <attr name="customTextColorDown" format="color" />
    <attr name="customBackgroundColorDown" format="color" />
    <attr name="customLetterDivHeight" format="dimension" />
    <attr name="customTextSize" format="dimension" />
    <attr name="customBackgroundAngle" format="integer" />
</declare-styleable>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。