首先看效果图
下面是代码部分自定义view部分代码如下
/**
* Created by Administrator on 2018/1/23.
* 列表页
*/
public class IndexList extends View {
Paint paint;
Context context;
int clickposition = -1;
String texts[] = 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"};
float lineHeight = -1;
public IndexList(Context context) {
this(context, null);
}
public IndexList(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public IndexList(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
paint = new Paint();
paint.setAntiAlias(true);
paint.setTextSize(sp2px(15));
paint.setColor(Color.BLUE);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
String text = "A";
float textWidth = paint.measureText(text, 0, text.length());
int width = (int) (getPaddingLeft() + getPaddingRight() + textWidth);
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
lineHeight = ((1.0f) * (getHeight() - getPaddingTop() - getPaddingBottom())) / texts.length;
for (int i = 0; i < texts.length; i++) {
float x = getPaddingLeft() + (getWidth() - getPaddingLeft() - getPaddingRight() - paint.measureText(texts[i])) / 2;
Paint.FontMetrics metrics = paint.getFontMetrics();
float y = getPaddingTop() + lineHeight * i + lineHeight / 2 + (metrics.bottom - metrics.top) / 2 - metrics.bottom;
if (clickposition == i) {
paint.setColor(Color.RED);
} else {
paint.setColor(Color.BLUE);
}
canvas.drawText(texts[i], x, y, paint);
}
}
private float sp2px(int sp) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return 0.5f + sp * displayMetrics.scaledDensity;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
float y = event.getY();
int newPosition = -1;
newPosition = (int) ((y - getPaddingTop()) / lineHeight);
if (newPosition < 0) newPosition = 0;
if (newPosition > texts.length) newPosition = texts.length;
if (newPosition != clickposition) {
clickposition = newPosition;
postInvalidate();
}
break;
}
return true;
// return super.onTouchEvent(event);
}
}
然后是调用部分
<com.testlist.IndexList
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:padding="10dp"/>
代码逻辑很简单如果大家需要点击的时候触发事件比如弹出pop可以在onTouchEvent中处理(最好使用回调处理)