posts - 11,  comments - 0,  trackbacks - 0

 目标是做一个牛叉的日历,但是要先一步步来,先看效果图

简单一点说就是吧自定义view平分成七个部分,每个部分写上一个字,然后自定义view可以跟随手指滑动,并在抬起手指后恢复到初始位置,并且点击view可以判断出点的是哪个view(都是用坐标算出来)

代码也简单,看一下就ok

public class AAAView extends View {

    private Paint paint;
    private float moveX;//移动距离
    private float downX;//手指按下的位置
    private int r;//每个字的半径
    private int d;//直径
    private int location;//手指按在哪个字上
    private Context context;

    public AAAView(Context context) {
        super(context);
        init(context);
    }

    public AAAView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public AAAView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(25);
        this.context = context;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        r = getWidth() / 14;
        d = 2 * r;
        for (int i = 0; i < 7; i++) {
            canvas.drawText("a", r + i * 2 * r + moveX, 30, paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                location = (int) Math.ceil(downX / d);
                return true;
            case MotionEvent.ACTION_MOVE:
                moveX = (int) (event.getX() - downX);
                invalidate();
                return true;
            case MotionEvent.ACTION_UP://每次抬起手势后,要恢复初始状态
                moveX = 0;
                invalidate();
                if (event.getX() < location * d && event.getX() > (location - 1) * d) {
                    Toast.makeText(context, "点击了第" + location + "个字", Toast.LENGTH_LONG).show();
                }
                return true;
        }
        return super.onTouchEvent(event);
    }
}

万事开头难,估计日历系列要写很久,不过慢慢来,应该可以搞定

posted on 2018-03-13 10:59 付斌 阅读(...) 评论(...) 编辑 收藏