Android 侧边索引自定义View

作者:MrTrying

前言

其实字母索引View已经有很多人都造过的轮子了,有使用ListVieworRecyclerView实现的,也有自定义View实现的,但是作为一个程序猿总会想有自己的轮子。所以百度了一下实现方式,使用自定义View,按照自己扩展思维实现了BindexNavigationView,下面是效果

效果图

这里说一下为什么不用ListVieworRecyclerView实现,现阶段需求并没有这么复杂,而对于侧边索引这个功能本身来说,并不需要使用ListView这么强大的扩展性;所以选择自定义View的方式

这里需要说明的是,实现的是UI和数据的填充,没有拼音自动匹配(后续会在Demo中实现),也没有炫酷的特效,如果你有其他的需求想直接找一个合适的轮子,本文可能不适合阅读,建议去看看其他的文章。

实现

索引需要的就是文字选中状态变化和已经选中状态的一个监听回调,而文字选中状态变化涉及到文字颜色、背景颜色。以上就是最基本的需求,接下来就知道需要做什么事情了。

自定义属性

attrs文件中添加以下的自定义属性


    
    
    
    
    
    
    
    

然后,在代码中获取这些自定义属性;这里还获取了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()这三个方法,不过这里的实现不需要使用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);
            }
        }
        //设置文字颜色
        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);
    }
}

监听事件的处理

通过实现onTouchEvent方法,计算当前触摸的坐标是属于哪个文字的区域的,得出当前选中的文字,并通知设置给View的回调

@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();
                }
                //通知选中回调
                notifyOnItemSelected(currentSelectIndex, indexBeanList.get(currentSelectIndex));
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            //do nothing
            break;
    }
    return true;
}

选中的回调接口就简单了,为外界提供了选中的index和选中的bean

/**选中监听*/
public interface OnItemSelectedListener {
    public void onItemSelected(int position, IndexBean bean);
}

在外部设置选中回调时做了一点点的扩展,使用了回调集合的方式,方便多方添加回调

private List 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();
}

这里基本主要的实现代码就都在这里了,考虑以后的扩展这里封装了IndexBean内部类来传递数据

/**索引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中提供设置文字选中和未选中颜色,以及选中的背景色或背景Drawable(背景Drawable优先于背景色)。


设置数据

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 indexBeans = new ArrayList<>();
for(String str:wrods){
    indexBeans.add(new BindexNavigationView.IndexBean(str));
}
navigationView.setData(indexBeans);

设置回调

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

总结

其实,还有很多地方需要后续继续完善,例如:调用代码选中对应位置;文字的背景直接使用selector;绘制时的代码效率和结构的优化等等。也欢迎大家指正

Demo地址

参考文章:

Android自定义View——实现联系人列表字母索引

你可能感兴趣的:(Android 侧边索引自定义View)