Android 自定义View之手势解锁控件 – 源码巴士 | 您所在的位置:网站首页 › 安卓自定义button › Android 自定义View之手势解锁控件 – 源码巴士 |
前言:Android有很多原生控件供开发者使用,但是原生控件使用起来也有局限性,这个时候呢Android也有给开发者提供一些方式来根据需求进行自定义,今天介绍自定义控件之手势解锁控件,效果如图 步骤四:处理按下和移动 抬起事件 @Override public boolean onTouchEvent(MotionEvent event) { if (mTouchable) { int action = event.getAction(); int x = (int) event.getX(); int y = (int) event.getY(); switch (action) { case MotionEvent.ACTION_DOWN: handleDownEvent(x, y); break; case MotionEvent.ACTION_MOVE: handleMoveEvent(x, y); break; case MotionEvent.ACTION_UP: handleUpEvent(); break; } invalidate(); return true; } else { return false; } }按下时需要复位View,处理移动事件 private void handleMoveEvent(int x, int y) { mPaint.setColor(mFingerTouchColor); ILockView lockView = getLockViewByPoint(x, y); if (lockView != null) { int childId = lockView.getView().getId(); if (!mChooseList.contains(childId)) { mChooseList.add(childId); lockView.onFingerTouch(); //手势解锁监听 if (mOnLockVerifyListener != null) { mOnLockVerifyListener.onGestureSelected(childId); } mLastPathX = lockView.getView().getLeft() / 2 + lockView.getView().getRight() / 2; mLastPathY = lockView.getView().getTop() / 2 + lockView.getView().getBottom() / 2; if (mChooseList.size() == 1) { mPath.moveTo(mLastPathX, mLastPathY); } else { mPath.lineTo(mLastPathX, mLastPathY); } } } //指引线终点坐标 mLineX = x; mLineY = y; }处理抬起事件: private void handleUpEvent() { if (mCurrentMode == RESET_MODE) { handleResetMode(); } else { handleVerifyMode(); } //将指引线的终点坐标设置为最后一个Path的原点,即取消指引线 mLineX = mLastPathX; mLineY = mLastPathY; }步骤五:记录和保存 @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.tryTimes = mTryTimes; return ss; }步骤六:校验 /** * 检查答案是否正确 */ private boolean checkAnswer() { if (mAnswerList.size() != mChooseList.size()) { return false; } for (int i = 0; i < mAnswerList.size(); i++) { if (mAnswerList.get(i) != mChooseList.get(i) - 1) { return false; } } return true; } /** * 切换LockView是否匹配状态 */ private void toggleLockViewMatchedState(boolean isMatched) { if (isMatched) { mPaint.setColor(mFingerUpMatchedColor); } else { mPaint.setColor(mFingerUpUnmatchedColor); } for (ILockView iLockView : mILockViews) { if (mChooseList.contains(iLockView.getView().getId())) { if (!isMatched) { iLockView.onFingerUpUnmatched(); } else { iLockView.onFingerUpMatched(); } } } }OK,结束 代码已经上传到 我的资源 |
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |