这是一个简单的字母索引组件类,可以直接使用。
package com.peng.lai.wedget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class LetterIndex extends View{
private int width;
private int heigth;
private float x;
private float y;
private float letterSize;
private int index = -1;
private char[] letters = {'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','#'};
private Paint mPaint;
private Paint mPaint2;
public LetterIndex(Context context) {
super(context);
}
public LetterIndex(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint2 = new Paint();
mPaint2.setColor(Color.RED);
mPaint2.setTextAlign(Paint.Align.CENTER);
}
public interface OnItemListener{
void onItemSelected(int index,String content);
}
private OnItemListener listener;
public void setOnItemListener(OnItemListener listener){
this.listener = listener;
}
public int getIndex(){
return index;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
heigth = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, heigth);
mPaint.setTextSize(heigth/27-20);
mPaint2.setTextSize(heigth/27-20);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_DOWN:
x = event.getX();
y = event.getY();
if(x>width-mPaint.measureText("A")*2){
index = (int)(y/(heigth/27));
if(index>=27){
index=26;
}
if(listener!=null){
listener.onItemSelected(index, letters[index]+"");
}
invalidate();
return true;
}
break;
default:
break;
}
return super.onTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
letterSize = mPaint.measureText("A");
for (int i = 0; i < 27; i++) {
if(index==i){
canvas.drawText(letters[i]+"", width-letterSize, heigth/27*(i+1), mPaint2);
}else{
canvas.drawText(letters[i]+"", width-letterSize, heigth/27*(i+1), mPaint);
}
}
}
}