public class MySideBar extends View { private OnTouchingLetterChangedListener onTouchingLetterChangedListener; public Paint paint=new Paint(); private int choose=-1;//选中的 public MySideBar(Context context) { super(context); } public MySideBar(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public MySideBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } private String[] words={"#","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"}; @Override protected void onDraw(Canvas canvas){ super.onDraw(canvas); int height=getHeight();//获取对应高度 int width=getWidth();//获取对应宽度 int singleHeight=height/words.length;//获取每一个字母高度 for (int i=0;i<words.length;i++){ //设置每一个字母的样式 paint.setColor(Color.BLACK); paint.setTypeface(Typeface.DEFAULT); paint.setAntiAlias(true); paint.setTextSize(30); //选中状态 if (i==choose){ paint.setColor(Color.RED); paint.setFakeBoldText(true); } float xpos=width/2-paint.measureText(words[i])/2; float ypos=singleHeight*i+singleHeight;//高度递增 canvas.drawText(words[i],xpos,ypos,paint); paint.reset();//重置画笔 } } public boolean dispatchTouchEvent(MotionEvent event){ final int action=event.getAction(); final float y=event.getY(); final int oldChoose=choose; final OnTouchingLetterChangedListener listener=onTouchingLetterChangedListener; final int c=(int)(y/getHeight()*words.length); switch (action){ case MotionEvent.ACTION_UP: setBackgroundDrawable(new ColorDrawable(0x00000000)); choose=-1; invalidate(); break; default: setBackgroundResource(R.drawable.blue); if (oldChoose != c) { if (c >= 0 && c < words.length) { if (listener != null) { listener.onTouchingLetterChanged(words[c]); } choose = c; invalidate(); } } break; } return true; } /** *向外公开的方法 * * @param onTouchingLetterChangedListener */ public void setOnTouchingLetterChangedListener( OnTouchingLetterChangedListener onTouchingLetterChangedListener) { this.onTouchingLetterChangedListener = onTouchingLetterChangedListener; } /** * 接口 * * @author coder * */ public interface OnTouchingLetterChangedListener { public void onTouchingLetterChanged(String s); } }
自定义SideBar---电话簿
最新推荐文章于 2020-05-28 20:11:25 发布