Android如何自定義字母導(dǎo)航欄

這篇文章主要為大家展示了“Android如何自定義字母導(dǎo)航欄”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Android如何自定義字母導(dǎo)航欄”這篇文章吧。

成都創(chuàng)新互聯(lián)公司成立與2013年,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站制作、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元文山州做網(wǎng)站,已為上家服務(wù),為文山州各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:18982081108

明確需求

字母導(dǎo)航欄在實(shí)際開發(fā)中還是比較多見的,城市選擇、名稱選擇等等可能需要到。 現(xiàn)在要做到的就是在滑動(dòng)控件過(guò)程中可以有內(nèi)容以及 下標(biāo)的回調(diào),方便處理其他邏輯!

整理思路

1、確定控件的尺寸,防止內(nèi)容顯示不全。相關(guān)的邏輯在onMeasure()方法中處理;2、繪制顯示的內(nèi)容,在按下和抬起不同狀態(tài)下文字、背景的顏色。相關(guān)邏輯在onDraw()方法中;3、滑動(dòng)事件的處理以及事件回調(diào)。相關(guān)邏輯在onTouchEvent()方法中;

動(dòng)手實(shí)現(xiàn)

在需求明確、思路清晰的情況下就要開始動(dòng)手實(shí)現(xiàn)(需要了解自定義View的一些基礎(chǔ)API)。核心代碼就onDraw()中。在代碼中有思路和注釋,可以結(jié)合代碼一起看看。如果有疑惑、優(yōu)化、錯(cuò)誤的地方請(qǐng)?jiān)谠u(píng)論區(qū)提出,共同進(jìn)步!

完整代碼

/** * 自定義字母導(dǎo)航欄 * * 總的來(lái)說(shuō)就四步 * 1、測(cè)量控件尺寸{@link #onMeasure(int, int)} * 2、繪制顯示內(nèi)容(背景以及字符){@link #onDraw(Canvas)} * 3、處理滑動(dòng)事件{@link #onTouchEvent(MotionEvent)} * 4、暴露接口{@link #setOnNavigationScrollerListener(OnNavigationScrollerListener)} * * @attr customTextColorDefault //導(dǎo)航欄默認(rèn)文字顏色 * @attr customTextColorDown //導(dǎo)航欄按下文字顏色 * @attr customBackgroundColorDown //導(dǎo)航欄按下背景顏色 * @attr customLetterDivHeight //導(dǎo)航欄內(nèi)容高度間隔 * @attr customTextSize //導(dǎo)航欄文字尺寸 * @attr customBackgroundAngle //導(dǎo)航欄背景角度 */public class CustomLetterNavigationView extends View {  private static final String TAG = "CustomLetterNavigation";  //導(dǎo)航內(nèi)容  private String[] mNavigationContent;  //導(dǎo)航欄內(nèi)容間隔  private float mContentDiv;  //導(dǎo)航欄文字大小  private float mContentTextSize;  //導(dǎo)航欄文字顏色  private int mContentTextColor;  //導(dǎo)航欄按下時(shí)背景顏色  private int mBackgroundColor;  //導(dǎo)航欄按下時(shí)圓角度數(shù)  private int mBackGroundAngle = 0;  //導(dǎo)航欄按下時(shí)文字顏色  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, attrs, defStyleAttr);    initDefaultData();//初始化默認(rèn)數(shù)據(jù)    initAttrs(context, attrs);  }  @Override  protected void onDraw(Canvas canvas) {    /**     * <P>     *   這里我們分為兩步     *     *   1、繪制背景     *    這里簡(jiǎn)單,直接調(diào)用Canvas的drawRoundRect()方法直接繪制     *   2、繪制顯示文本     *    繪制文字首先要定位,定位每個(gè)字符的坐標(biāo)     *    X軸簡(jiǎn)單,寬度的一半     *    Y軸坐標(biāo)通過(guò)每個(gè)字符的高h(yuǎn)eightShould乘以已繪制字符的數(shù)目     * </P>     */    int mViewWidth = getWidth();    //繪制背景    mRectF.set(0, 0, mViewWidth, getHeight());    if (mEventActionState) {      mTextPaint.setColor(mDownContentTextColor);      mPaintBackgrount.setColor(mBackgroundColor);      canvas.drawRoundRect(mRectF, mBackGroundAngle, 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, mBackGroundAngle, mBackGroundAngle, mPaintBackgrount);    }    //繪制文本    float textX = mViewWidth / 2;    //X軸坐標(biāo)    int contentLenght = getContentLength();    //Y軸坐標(biāo)(這里在測(cè)量的時(shí)候多加入了兩個(gè)間隔高度要減去,同時(shí)還有Padding值)    float heightShould = (getHeight() - mContentDiv * 2 - getPaddingTop() - getPaddingBottom()) / contentLenght;    for (int i = 0; i < contentLenght; i++) {      //計(jì)算Y軸的坐標(biāo)      float startY = ((i + 1) * heightShould) + getPaddingTop();      //繪制文字      canvas.drawText(mNavigationContent[i], textX, startY, mTextPaint);    }  }  @Override  public boolean onTouchEvent(MotionEvent event) {    /**     * 這里主要處理手指滑動(dòng)事件     */    float mEventY = event.getY();    switch (event.getAction()) {      case MotionEvent.ACTION_DOWN:        //手指按下的時(shí)候,修改Enent狀態(tài)、重繪背景、觸發(fā)回調(diào)        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:        //手指離開的時(shí)候,修改Enent狀態(tài)、重繪背景、觸發(fā)回調(diào)        mEventActionState = false;        invalidate();        if (mOnNavigationScrollerListener != null) {          mOnNavigationScrollerListener.onUp();        }        break;    }    return true;  }  @Override  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    super.onMeasure(widthMeasureSpec, heightMeasureSpec);    /**     * <p>     *   這里做了簡(jiǎn)單的適應(yīng),其目的就是為了能夠正常的顯示我們的內(nèi)容     *     *   不管設(shè)置的是真實(shí)尺寸或者是包裹內(nèi)容,都會(huì)以內(nèi)容的最小尺寸為     *   基礎(chǔ),如果設(shè)置的控件尺寸大于我們內(nèi)容的最小尺寸,就使用控件     *   尺寸,反之使用內(nèi)容的最小尺寸!     * </p>     */    int widhtMode = MeasureSpec.getMode(widthMeasureSpec);    int heightMode = MeasureSpec.getMode(heightMeasureSpec);    //獲取控件的尺寸    int actualWidth = MeasureSpec.getSize(widthMeasureSpec);    int actualHeight = MeasureSpec.getSize(heightMeasureSpec);    int contentLegth = getContentLength();    //計(jì)算一個(gè)文字的尺寸    Rect mRect = measureTextSize();    //內(nèi)容的最小寬度    float contentWidth = mRect.width() + mContentDiv * 2;    //內(nèi)容的最小高度    float contentHeight = mRect.height() * contentLegth + mContentDiv * (contentLegth + 3);    if (MeasureSpec.AT_MOST == widhtMode) {      //寬度包裹內(nèi)容      actualWidth = (int) contentWidth + getPaddingLeft() + getPaddingRight();    } else if (MeasureSpec.EXACTLY == widhtMode) {      //寬度限制      if (actualWidth < contentWidth) {        actualWidth = (int) contentWidth + getPaddingLeft() + getPaddingRight();      }    }    if (MeasureSpec.AT_MOST == heightMode) {      //高度包裹內(nèi)容      actualHeight = (int) contentHeight + getPaddingTop() + getPaddingBottom();    } else if (MeasureSpec.EXACTLY == widhtMode) {      //高度限制      if (actualHeight < contentHeight) {        actualHeight = (int) contentHeight + getPaddingTop() + getPaddingBottom();      }    }    setMeasuredDimension(actualWidth, actualHeight);  }  /**   * 初始化默認(rèn)數(shù)據(jù)   */  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();  }  /**   * 獲取內(nèi)容長(zhǎng)度   *   * @return 內(nèi)容長(zhǎng)度   */  private int getContentLength() {    if (mNavigationContent != null) {      return mNavigationContent.length;    }    return 0;  }  /**   * 滑動(dòng)計(jì)算   *   * @param mEventY Y軸滑動(dòng)距離   */  private void scrollCount(float mEventY) {    //滑動(dòng)的時(shí)候利用滑動(dòng)距離和每一個(gè)字符高度進(jìn)行取整,獲取到Index    Rect mRect = measureTextSize();    int index = (int) ((mEventY - getPaddingTop() - getPaddingBottom() - mContentDiv * 2) / (mRect.height() + mContentDiv));    //防止越界    if (index >= 0 && index < getContentLength()) {      String newLetter = mNavigationContent[index];      //防止重復(fù)觸發(fā)回調(diào)      if (!mCurrentLetter.equals(newLetter)) {        mCurrentLetter = newLetter;        if (mOnNavigationScrollerListener != null) {          mOnNavigationScrollerListener.onScroll(mCurrentLetter, index);        }      }    }  }  /**   * 測(cè)量文字的尺寸   *   * @return 一個(gè)漢字的矩陣   */  public Rect measureTextSize() {    Rect mRect = new Rect();    if (mTextPaint != null) {      mTextPaint.getTextBounds("田", 0, 1, mRect);    }    return mRect;  }  /**   * 設(shè)置導(dǎo)航欄滑動(dòng)監(jiān)聽   *   * @param onNavigationScrollerListener   */  public void setOnNavigationScrollerListener(OnNavigationScrollerListener onNavigationScrollerListener) {    this.mOnNavigationScrollerListener = onNavigationScrollerListener;  }  /**   * 設(shè)置導(dǎo)航欄顯示內(nèi)容   *   * @param content 需要顯示的內(nèi)容   */  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));      }    }    //需要重新測(cè)量    requestLayout();  }  public interface OnNavigationScrollerListener {    //按下    void onDown();    //滑動(dòng)    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>

以上是“Android如何自定義字母導(dǎo)航欄”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

網(wǎng)頁(yè)題目:Android如何自定義字母導(dǎo)航欄
文章來(lái)源:http://bm7419.com/article10/jddsgo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗(yàn)、App設(shè)計(jì)、ChatGPT、外貿(mào)建站、響應(yīng)式網(wǎng)站、標(biāo)簽優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)