这是我写的一个自定义VIew: 联系人字母搜索表
首先,设置atrss
设置的attr标签下可以设置选中或者未选中的字母表中字母的颜色,若为设置,在view类中有默认的颜色
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LetterView">
<attr name="select_color" format="color"/>
<attr name="unselect" format="color"/>
</declare-styleable>
</resources>
接下来是自定义view类的实例代码
public class LetterView extends View{
private Paint paint;
private int count;
private int single;
private int chooseLetter;
private TextView bigLetter;
private int chooseColor;
private int defaultColor;
private static final String[] 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"};
public LetterView(Context context) {
this(context, null);
}
public LetterView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LetterView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//获取自定义属性 1 AttributeSet属性的集合 2 自定义的属性 3默认的属性值 4默认的资源
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.LetterView, defStyleAttr, 0);
defaultColor = typedArray.getColor(R.styleable.LetterView_unselect, Color.BLACK);
chooseColor = typedArray.getColor(R.styleable.LetterView_select_color, Color.RED);
typedArray.recycle();
paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(20);
chooseLetter = -1;
}
//获取导航显示大字母的View
public void setBigLetter(TextView bigLetter){
this.bigLetter = bigLetter;
bigLetter.setVisibility(GONE);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//获取View的高度和宽度
int height = getHeight();
int width = getWidth();
//计算一个字母的高度
count = LETTERS.length;
single = height/count;
for(int i = 0; i < count; i++){
//计算一个字母的宽度
int x = (int)(paint.measureText(LETTERS[i]));
if(i == chooseLetter){
paint.setColor(chooseColor);
paint.setTextSize(40);
} else {
paint.setColor(defaultColor);
paint.setTextSize(20);
}
canvas.drawText(LETTERS[i], width/2-x/2, (i+1) * single, paint);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
//获取点击或触摸的位置的Y坐标
float y = event.getY();
int position = (int)(y / single);
if(position >= 0 && position < LETTERS.length){
chooseLetter = position;
bigLetter.setVisibility(VISIBLE);
bigLetter.setText(LETTERS[chooseLetter]);
invalidate();
}
break;
case MotionEvent.ACTION_UP:
chooseLetter = -1;
bigLetter.setVisibility(GONE);
invalidate();
break;
}
return true;
}
}