一直想着做一个索引,毕竟索引也是常用的比如城市选择、通讯录什么的。所以昨天就写了一个,今天在这里贴下代码,以后肯定用得到,废话不多说,操起键盘就是干。
由于列表用到了我自己封装的RecyclerView,所以先让大家看下包结构
model包下:是不同类型的item类。貌似说了也没卵用,上效果图压压惊:
这下明白了把,他们有实现了一个接口就是utils包下的BaseStickyBean
里面有个提取汉字的首字母的,用来排序。
接下来我就开始一本正经的将代码啦:
先看右侧自定义控件:
package app.project.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import app.project.R;
/**
* @author qly
*/
public class MySlideBar extends View {
// 是否点击
private boolean showBkg = false;
// 监听面板是否点击接口
OnTouchingLetterChangedListener onTouchingLetterChangedListener;
// 26个字母
public static String[] b = { "#", "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" };
// 选择的值
int choose = -1;
private Context context;
// 画笔
Paint paint = new Paint();
public MySlideBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
public MySlideBar(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public MySlideBar(Context context) {
super(context);
this.context = context;
}
/**
* 重写这个方法
*/
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//背景色绘制为灰色
if (showBkg) {
canvas.drawColor(Color.parseColor("#40000000"));
}
int height = getHeight();
int width = getWidth();
int singleHeight = height / b.length;
for (int i = 0; i < b.length; i++) {
paint.setAntiAlias(true);
paint.setTextSize(context.getResources().getDimensionPixelSize(
R.dimen.sidebar_textsize));
// 点击的字体和26个字母中的任意一个相等就
if (i == choose) {
paint.setColor(Color.parseColor("#3399ff"));
paint.setFakeBoldText(true);
}
// 字体的X坐标