像很多的应用程序里面都有个管理联系人的导航栏,即:26个大写字母竖排显示在右侧,然后点击一个字母,listview会自动筛选分组;下面是一个自定义的view,绘制的右侧导航,即:把右侧的导航作为一个单独的View来使用,可以作为一个工具的View,随时随地的使用!
`/**
* 利用自定义View 绘制右侧导航
* @author fz
*
*/
public class MyView extends View {
public static String[] letter={"热门","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"};
Paint paint;
OnTouchLetterListener listener;
// 调用这个方法来进行回调
public void setOnTouchListener(OnTouchLetterListener listener){
this.listener=listener;
}
// 构造器
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initPaint();
}
//画笔
private void initPaint() {
paint=new Paint(Paint.ANTI_ALIAS_FLAG);//设置抗锯齿效果
paint.setTextSize(TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
11, // 设置字体大小
getResources().getDisplayMetrics()));
}
// 重写绘制方法
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//自定义view分配给每个字符串的高度
int height=getHeight()/letter.length;
//自定义view分配给每个字符串的宽度
int width=getWidth();
//利用循环全部绘制出来
for(int i=0;i<letter.length;i++){
Rect bounds=new Rect();
paint.getTextBounds(letter[i], 0, letter[i].length(), bounds);
//横坐标
float x=width/2-bounds.width()/2;
//纵坐标
float y=height/2+bounds.height()/2+height*i;
// 绘制字体
canvas.drawText(letter[i], x, y, paint);
}
}
// 重写,触摸事件这个方法
@Override
public boolean onTouchEvent(MotionEvent event) {
int action=event.getAction();
// 四个触摸事件:落下,移动,抬起,取消
switch (action) {
//这里只写了按下和移动
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
//添加灰色背景
setBackgroundColor(Color.LTGRAY);
//根据手指当前位置换算出当前手指所在的字符
float ypos=event.getY();
int idx=(int) ((ypos*letter.length)/getHeight());
//设置监听器,利用回调方法,把字符传过去
if(idx>=0&&idx<letter.length){
if(listener!=null){
listener.onTouchsetLetter(letter[idx]);
}
}
break;
default:
setBackgroundColor(Color.TRANSPARENT);//透明色
break;
}
return true;
}
// 内部接口,监听器,
public interface OnTouchLetterListener{
void onTouchsetLetter(String letter);
}
}`
回调方法的使用:即在listview显示的分组界面进行调用
myview.setOnTouchListener(new OnTouchLetterListener() {
@Override
public void onTouchsetLetter(String letter) {
if(letter.equals("热门")){
listview.setSelection(0);
}else{
char section=letter.charAt(0);
listview.setSelection(adapter.getPositionForSection(section));
}
}
});