Android 側(cè)邊索引自定義View

作者:MrTrying

前言

其實(shí)字母索引View已經(jīng)有很多人都造過的輪子了,有使用ListVieworRecyclerView實(shí)現(xiàn)的,也有自定義View實(shí)現(xiàn)的,但是作為一個程序猿總會想有自己的輪子。所以百度了一下實(shí)現(xiàn)方式,使用自定義View,按照自己擴(kuò)展思維實(shí)現(xiàn)了BindexNavigationView,下面是效果

效果圖

這里說一下為什么不用ListVieworRecyclerView實(shí)現(xiàn),現(xiàn)階段需求并沒有這么復(fù)雜,而對于側(cè)邊索引這個功能本身來說,并不需要使用ListView這么強(qiáng)大的擴(kuò)展性;所以選擇自定義View的方式

這里需要說明的是,實(shí)現(xiàn)的是UI和數(shù)據(jù)的填充,沒有拼音自動匹配(后續(xù)會在Demo中實(shí)現(xiàn)),也沒有炫酷的特效,如果你有其他的需求想直接找一個合適的輪子,本文可能不適合閱讀,建議去看看其他的文章。

實(shí)現(xiàn)

索引需要的就是文字選中狀態(tài)變化和已經(jīng)選中狀態(tài)的一個監(jiān)聽回調(diào),而文字選中狀態(tài)變化涉及到文字顏色、背景顏色。以上就是最基本的需求,接下來就知道需要做什么事情了。

自定義屬性

attrs文件中添加以下的自定義屬性

<declare-styleable name="BindexNavigationView">
    <!--選中文字顏色-->
    <attr name="selectedTextColor" format="color"/>
    <!--未選中文字顏色-->
    <attr name="unselectedTextColor" format="color"/>
    <!--選中文字背景顏色-->
    <attr name="selectedBackgroundColor" format="color"/>
    <!--選中文字背景Drawable-->
    <attr name="selectedBackgroundDrawable" format="reference"/>
</declare-styleable>

然后,在代碼中獲取這些自定義屬性;這里還獲取了android:textSize屬性,來控制文字大小

private void initialize(Context context, AttributeSet attrs, int defStyleAttr) {
    if (attrs != null) {
        TypedArray originalAttrs = context.obtainStyledAttributes(attrs, ANDROID_ATTRS);
        textSize = originalAttrs.getDimensionPixelSize(0, textSize);
        gravity = originalAttrs.getInt(1, gravity);
        originalAttrs.recycle();

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BindexNavigationView);
        selectedTextColor = a.getColor(R.styleable.BindexNavigationView_selectedTextColor, selectedTextColor);
        unselectedTextColor = a.getColor(R.styleable.BindexNavigationView_unselectedTextColor, unselectedTextColor);
        selectedBackgroundColor = a.getColor(R.styleable.BindexNavigationView_selectedBackgroundColor, selectedBackgroundColor);
        selectedBackgroundDrawable = a.getDrawable(R.styleable.BindexNavigationView_selectedBackgroundDrawable);
        a.recycle();
    }

    wordsPaint = new Paint();
    wordsPaint.setColor(unselectedTextColor);
    wordsPaint.setTextSize(textSize);
    wordsPaint.setAntiAlias(true);
    wordsPaint.setTextAlign(Paint.Align.CENTER);

    bgPaint = new Paint();
    bgPaint.setAntiAlias(true);
    bgPaint.setColor(selectedBackgroundColor);

    onItemSelectedListeners = new ArrayList<>();
}

背景和文字的測量和繪制

自定義View基本都需要重寫onMeasure()、onLayout()onDraw()這三個方法,不過這里的實(shí)現(xiàn)不需要使用onLayout()方法,這里更多的代碼是計算文字和文字背景的繪制的位置,主要的代碼還是在onDraw()中。

Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    //獲取文字的寬
    itemWidth = getMeasuredWidth();
    int height = getMeasuredHeight();
    int realHeight = itemWidth * indexBeanList.size();
    //計算距離頂部的offset
    if (height > realHeight) {
        offsetTop = (height - realHeight) / 2 + getPaddingTop();
    }
    //計算文字的高
    itemHeight = realHeight / indexBeanList.size();
}

Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    for (int i = 0; i < indexBeanList.size(); i++) {
        boolean isSelected = i == currentSelectIndex;
        if (isSelected) {
            //繪制選中背景
            if (selectedBackgroundDrawable != null) {
                //繪制drawable
                RectF rectF = new RectF();
                rectF.left = getPaddingLeft();
                rectF.top = itemHeight * i + offsetTop;
                rectF.right = rectF.left + itemWidth;
                rectF.bottom = rectF.top + itemHeight;
                canvas.saveLayer(rectF,null,Canvas.ALL_SAVE_FLAG);
                selectedBackgroundDrawable.setBounds((int) (rectF.left), (int) rectF.top, (int) rectF.right, (int) rectF.bottom);
                selectedBackgroundDrawable.draw(canvas);
                canvas.restore();
            } else {
                //繪制背景色
                canvas.drawCircle(itemWidth / 2, itemHeight * i + itemHeight / 2 + offsetTop, itemWidth / 2, bgPaint);
            }
        }
        //設(shè)置文字顏色
        wordsPaint.setColor(isSelected ? selectedTextColor : unselectedTextColor);
        //獲取文字高度
        Rect rect = new Rect();
        String word = indexBeanList.get(i).getIndexValue();
        wordsPaint.getTextBounds(word, 0, 1, rect);
        int wordHeight = rect.height();
        //繪制字母
        float wordX = itemWidth / 2;
        float wordY = wordHeight / 2 + itemHeight * i + itemHeight / 2 + offsetTop;
        canvas.drawText(word, wordX, wordY, wordsPaint);
    }
}

監(jiān)聽事件的處理

通過實(shí)現(xiàn)onTouchEvent方法,計算當(dāng)前觸摸的坐標(biāo)是屬于哪個文字的區(qū)域的,得出當(dāng)前選中的文字,并通知設(shè)置給View的回調(diào)

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            float y = event.getY();
            //計算選中文字的index
            final int index = (int) ((y - offsetTop) / itemHeight);
            if (index >= 0 && index < indexBeanList.size()) {
                if (index != currentSelectIndex) {
                    currentSelectIndex = index;
                    invalidate();
                }
                //通知選中回調(diào)
                notifyOnItemSelected(currentSelectIndex, indexBeanList.get(currentSelectIndex));
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            //do nothing
            break;
    }
    return true;
}

選中的回調(diào)接口就簡單了,為外界提供了選中的index和選中的bean

/**選中監(jiān)聽*/
public interface OnItemSelectedListener {
    public void onItemSelected(int position, IndexBean bean);
}

在外部設(shè)置選中回調(diào)時做了一點(diǎn)點(diǎn)的擴(kuò)展,使用了回調(diào)集合的方式,方便多方添加回調(diào)

private List<OnItemSelectedListener> onItemSelectedListeners;

public boolean addOnItemSelectedListener(OnItemSelectedListener listener) {
    return listener != null && !onItemSelectedListeners.contains(listener) &&
            onItemSelectedListeners.add(listener);
}

public boolean removeOnItemSelectedListener(OnItemSelectedListener listener) {
    return listener != null && onItemSelectedListeners.remove(listener);
}

public void removeAllOnItemSelectedListener() {
    onItemSelectedListeners.clear();
}

這里基本主要的實(shí)現(xiàn)代碼就都在這里了,考慮以后的擴(kuò)展這里封裝了IndexBean內(nèi)部類來傳遞數(shù)據(jù)

/**索引Bean*/
public static class IndexBean {
    String type;
    final String indexValue;

    public IndexBean(@NonNull String indexValue) {
        this.indexValue = indexValue;
    }

    public String getIndexValue() {
        return TextUtils.isEmpty(indexValue) ? "" : indexValue;
    }
}

使用

XML屬性使用

xml中提供設(shè)置文字選中和未選中顏色,以及選中的背景色或背景Drawable(背景Drawable優(yōu)先于背景色)。

<com.mrtrying.widget.BindexNavigationView
    android:id="@+id/bindexNavigationView"
    android:layout_width="20dp"
    android:layout_height="match_parent"
    android:layout_alignParentRight="true"
    android:textSize="10sp"
    app:selectedBackgroundColor="@color/colorPrimary"
    app:selectedBackgroundDrawable="@drawable/bg_select"
    app:unselectedTextColor="@color/colorPrimary"
    app:selectedTextColor="@color/colorAccent"/>

設(shè)置數(shù)據(jù)

BindexNavigationView navigationView = findViewById(R.id.bindexNavigationView);
String[] wrods = {"↑", "☆", "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","#"};
ArrayList<BindexNavigationView.IndexBean> indexBeans = new ArrayList<>();
for(String str:wrods){
    indexBeans.add(new BindexNavigationView.IndexBean(str));
}
navigationView.setData(indexBeans);

設(shè)置回調(diào)

navigationView.addOnItemSelectedListener(new BindexNavigationView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(int position, BindexNavigationView.IndexBean bean) {
        textView.setText(bean.getIndexValue());
    }
});

總結(jié)

其實(shí),還有很多地方需要后續(xù)繼續(xù)完善,例如:調(diào)用代碼選中對應(yīng)位置;文字的背景直接使用selector;繪制時的代碼效率和結(jié)構(gòu)的優(yōu)化等等。也歡迎大家指正

Demo地址

參考文章:

Android自定義View——實(shí)現(xiàn)聯(lián)系人列表字母索引

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言 其實(shí)字母索引View已經(jīng)有很多人都造過的輪子了,有使用ListVieworRecyclerView實(shí)現(xiàn)的,也...
    MrTrying閱讀 432評論 0 3
  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,224評論 3 119
  • 有那么一瞬間,因為一個人的一句話,就像被潑了一盆涼水一樣,唰的一下,從頭冷到腳,語言這東西,在表達(dá)愛意的時候是那么...
    A分享閱讀 2,308評論 2 2
  • “我去找星巴克了?!?,說完這句話后,我便沿著僑城東路去尋找上次迷路時瞥見的星巴克了。 那是一家社區(qū)店,上次我...
    東孫飛閱讀 274評論 2 6

友情鏈接更多精彩內(nèi)容