作者: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)化等等。也歡迎大家指正