前言:
android 开发技术多如繁星,完全掌握非一日之功,开发涉及的深度难以想象,越走越难,金字塔顶尖上的人越来越少,今天得demo主要涉及的是自定义组件,很多时候,我们在网上找了太多资料,要么时代久远、要么表达不清、要么知识零碎、要么思路紊乱,随之而来的是不堪重负的挫败感和失落感,导致信心直线下降,而这些,正是我们面临的问题。
demo样式展示:
1.简说:
android 中组件必须是View的直接子类和间接子类,其中view有一个为viewGroup的子类,用于定义容器组件类,线性布局等,
如果组件中还有子组件就一定是从viewGroup类继承,否则从view类继承。View 类定义了组件相关的通用功能,并打通了组件在 Activity 整个活动周期中的绘制流程和效果等任督二脉,通过 OOP 构建出基本的运行框架,作为开发者,了解并掌握 View 的工作原理是非常必要的。
2,关系流程图
从图上可知:
1) Activity 类似于一个框架,负责容器生命周期及活动,窗口通过 Window 来管理;
2) Window 负责窗口管理(实际是子类 PhoneWindow),窗口的绘制和渲染交给 DecorView
完成;
3) DecorView 是 View 树的根,开发人员为 Activity 定义的 layout 将成为 DecorView 的子
视图 ContentParent 的子视图(有点拗口,但确实是这样);
4) layout.xml 是开发人员定义的布局文件,最终 inflate 为 DecorView 的子组件。
View 类的 draw()方法是组件绘制的核心方法,主要做了下面几件事:
1) 绘制背景:background.draw(canvas)
2) 绘制自己:onDraw(canvas)
3) 绘制子视图:dispatchDraw(canvas)
4) 绘制滚动条:onDrawScrollBars(canvas)
3.我们为什么要自定义view?
当系统提供给我们的组件满足不了我们的需求时,为了做出更绚丽的效果,我们自定义view来实现我们的需求.
4.我们为自定义view分为四类:
1)view重写onDraw方法
主要实现一些不规则效果,静态或者动态显示不规则图形,不方便通过布局组合方式实现,需要自己支wrap_content,padding也需要自己处理;
2)继承viewGroup,派生特殊的layout我们实现自定的布局,除了系统提供的三种布局之外,自己定义一个布局,用来显示几种view组合在一起的布局。这个方法略复杂。需要合适处理wrap_content测量,布局两个过程,
3)继承特点的view(textView)扩展已有的功能,不需要自己支持wrap_content和padding;
4)几种view组合在一起,不需要处理viewGroup的测量和布局这两个过程;
5.自定义view时的注意事项;
1)让view支持wrap_content因为我们在继承view或者viewGroup时,在measure中对wrap_content进行特殊处理,当外部使用wrap_content时候,会达不到我们预期的效果;
2)让view支持padding当我们继承view控件时,应在draw方法中对padding进行处理,如果不做处理padding会失效;继承viewGroup控件时;应该在measure和onlayout中考虑padding和子元素margin带来的影响,不然导致padding和子元素的margin失效;
3)尽量不要再view中使用handler因为view本身带有一系类post方法,可以代替handler作用,除非明确的使用handler发送消息;
4)view带有滑动嵌套时,需要处理好滑动冲突。如果有滑动冲突,会对效果造成影响
5)view有线程和动画需要及时停止;view变得不可见时,需要停止线程和动画,如果处理不及时,会造成内存泄露;
6.开始主题,手势滑动的密码锁,(直接代码)
1)绘制样式
public class GestureContentView extends ViewGroup {private int baseNum = 6;private int[] screenDispaly;/*** 每个点区域的宽度*/private int blockWidth;/*** 声明一个集合用来封装坐标集合*/private List<GesturePoint> list;private Context context;private boolean isVerify;private GestureDrawline gestureDrawline;/*** 包含9个ImageView的容器,初始化** @param context* @param isVerify 是否为校验手势密码* @param passWord 用户传入密码* @param callBack 手势绘制完毕的回调*/public GestureContentView(Context context, boolean isVerify, String passWord, GestureDrawline.GestureCallBack callBack) {super(context);screenDispaly = AppUtil.getScreenDispaly(context);blockWidth = screenDispaly[0] / 3;this.list = new ArrayList<GesturePoint>();this.context = context;this.isVerify = isVerify;// 添加9个图标addChild();// 初始化一个可以画线的viewgestureDrawline = new GestureDrawline(context, list, isVerify, passWord, callBack);}private void addChild() {for (int i = 0; i < 9; i++) {ImageView image = new ImageView(context);image.setBackgroundResource(R.drawable.gesture_node_normal);this.addView(image);invalidate();// 第几行int row = i / 3;// 第几列int col = i % 3;// 定义点的每个属性int leftX = col * blockWidth + blockWidth / baseNum;int topY = row * blockWidth + blockWidth / baseNum;int rightX = col * blockWidth + blockWidth - blockWidth / baseNum;int bottomY = row * blockWidth + blockWidth - blockWidth / baseNum;GesturePoint p = new GesturePoint(leftX, rightX, topY, bottomY, image, i + 1);this.list.add(p);}}public void setParentView(ViewGroup parent) {// 得到屏幕的宽度int width = screenDispaly[0];LayoutParams layoutParams = new LayoutParams(width, width);this.setLayoutParams(layoutParams);gestureDrawline.setLayoutParams(layoutParams);parent.addView(gestureDrawline);parent.addView(this);}@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {for (int i = 0; i < getChildCount(); i++) {//第几行int row = i / 3;//第几列int col = i % 3;View v = getChildAt(i);v.layout(col * blockWidth + blockWidth / baseNum, row * blockWidth + blockWidth / baseNum,col * blockWidth + blockWidth - blockWidth / baseNum, row * blockWidth + blockWidth - blockWidth / baseNum);}}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);// 遍历设置每个子view的大小for (int i = 0; i < getChildCount(); i++) {View v = getChildAt(i);v.measure(widthMeasureSpec, heightMeasureSpec);}}/*** 保留路径delayTime时间长** @param delayTime*/public void clearDrawlineState(long delayTime) {gestureDrawline.clearDrawlineState(delayTime);}}
2)绘制手势滑动
public class GestureDrawline extends View {private int mov_x;// 声明起点坐标private int mov_y;private Paint paint;// 声明画笔private Canvas canvas;// 画布private Bitmap bitmap;// 位图private List<GesturePoint> list;// 装有各个view坐标的集合private List<Pair<GesturePoint, GesturePoint>> lineList;// 记录画过的线private Map<String, GesturePoint> autoCheckPointMap;// 自动选中的情况点private boolean isDrawEnable = true; // 是否允许绘制/*** 屏幕的宽度和高度*/private int[] screenDispaly;/*** 手指当前在哪个Point内*/private GesturePoint currentPoint;/*** 用户绘图的回调*/private GestureCallBack callBack;/*** 用户当前绘制的图形密码*/private StringBuilder passWordSb;/*** 是否为校验*/private boolean isVerify;/*** 用户传入的passWord*/private String passWord;public GestureDrawline(Context context, List<GesturePoint> list, boolean isVerify,String passWord, GestureCallBack callBack) {super(context);screenDispaly = AppUtil.getScreenDispaly(context);paint = new Paint(Paint.DITHER_FLAG);// 创建一个画笔bitmap = Bitmap.createBitmap(screenDispaly[0], screenDispaly[0], Bitmap.Config.ARGB_8888); // 设置位图的宽高canvas = new Canvas();canvas.setBitmap(bitmap);paint.setStyle(Paint.Style.STROKE);// 设置非填充paint.setStrokeWidth(10);// 笔宽5像素paint.setColor(Color.rgb(245, 142, 33));// 设置默认连线颜色paint.setAntiAlias(true);// 不显示锯齿this.list = list;this.lineList = new ArrayList<Pair<GesturePoint, GesturePoint>>();initAutoCheckPointMap();this.callBack = callBack;// 初始化密码缓存this.isVerify = isVerify;this.passWordSb = new StringBuilder();this.passWord = passWord;}private void initAutoCheckPointMap() {autoCheckPointMap = new HashMap<String,GesturePoint>();autoCheckPointMap.put("1,3", getGesturePointByNum(2));autoCheckPointMap.put("1,7", getGesturePointByNum(4));autoCheckPointMap.put("1,9", getGesturePointByNum(5));autoCheckPointMap.put("2,8", getGesturePointByNum(5));autoCheckPointMap.put("3,7", getGesturePointByNum(5));autoCheckPointMap.put("3,9", getGesturePointByNum(6));autoCheckPointMap.put("4,6", getGesturePointByNum(5));autoCheckPointMap.put("7,9", getGesturePointByNum(8));}private GesturePoint getGesturePointByNum(int num) {for (GesturePoint point : list) {if (point.getNum() == num) {return point;}}return null;}// 画位图@Overrideprotected void onDraw(Canvas canvas) {// super.onDraw(canvas);canvas.drawBitmap(bitmap, 0, 0, null);}// 触摸事件@Overridepublic boolean onTouchEvent(MotionEvent event) {if (isDrawEnable == false) {// 当期不允许绘制return true;}paint.setColor(Color.rgb(245, 142, 33));// 设置默认连线颜色switch (event.getAction()) {case MotionEvent.ACTION_DOWN:mov_x = (int) event.getX();mov_y = (int) event.getY();// 判断当前点击的位置是处于哪个点之内currentPoint = getPointAt(mov_x, mov_y);if (currentPoint != null) {currentPoint.setPointState(Constants.POINT_STATE_SELECTED);passWordSb.append(currentPoint.getNum());}// canvas.drawPoint(mov_x, mov_y, paint);// 画点invalidate();break;case MotionEvent.ACTION_MOVE:clearScreenAndDrawList();// 得到当前移动位置是处于哪个点内GesturePoint pointAt = getPointAt((int) event.getX(), (int) event.getY());// 代表当前用户手指处于点与点之前if (currentPoint == null && pointAt == null) {return true;} else {// 代表用户的手指移动到了点上if (currentPoint == null) {// 先判断当前的point是不是为null// 如果为空,那么把手指移动到的点赋值给currentPointcurrentPoint = pointAt;// 把currentPoint这个点设置选中为true;currentPoint.setPointState(Constants.POINT_STATE_SELECTED);passWordSb.append(currentPoint.getNum());}}if (pointAt == null || currentPoint.equals(pointAt) || Constants.POINT_STATE_SELECTED == pointAt.getPointState()) {// 点击移动区域不在圆的区域,或者当前点击的点与当前移动到的点的位置相同,或者当前点击的点处于选中状态// 那么以当前的点中心为起点,以手指移动位置为终点画线canvas.drawLine(currentPoint.getCenterX(), currentPoint.getCenterY(), event.getX(), event.getY(), paint);// 画线} else {// 如果当前点击的点与当前移动到的点的位置不同// 那么以前前点的中心为起点,以手移动到的点的位置画线canvas.drawLine(currentPoint.getCenterX(), currentPoint.getCenterY(), pointAt.getCenterX(), pointAt.getCenterY(), paint);// 画线pointAt.setPointState(Constants.POINT_STATE_SELECTED);// 判断是否中间点需要选中GesturePoint betweenPoint = getBetweenCheckPoint(currentPoint, pointAt);if (betweenPoint != null && Constants.POINT_STATE_SELECTED != betweenPoint.getPointState()) {// 存在中间点并且没有被选中Pair<GesturePoint, GesturePoint> pair1 = new Pair<GesturePoint, GesturePoint>(currentPoint, betweenPoint);lineList.add(pair1);passWordSb.append(betweenPoint.getNum());Pair<GesturePoint, GesturePoint> pair2 = new Pair<GesturePoint, GesturePoint>(betweenPoint, pointAt);lineList.add(pair2);passWordSb.append(pointAt.getNum());// 设置中间点选中betweenPoint.setPointState(Constants.POINT_STATE_SELECTED);// 赋值当前的point;currentPoint = pointAt;} else {Pair<GesturePoint, GesturePoint> pair = new Pair<GesturePoint, GesturePoint>(currentPoint, pointAt);lineList.add(pair);passWordSb.append(pointAt.getNum());// 赋值当前的point;currentPoint = pointAt;}}invalidate();break;case MotionEvent.ACTION_UP:// 当手指抬起的时候if (isVerify) {// 手势密码校验// 清掉屏幕上所有的线,只画上集合里面保存的线if (passWord.equals(passWordSb.toString())) {// 代表用户绘制的密码手势与传入的密码相同callBack.checkedSuccess();} else {// 用户绘制的密码与传入的密码不同。callBack.checkedFail();}} else {callBack.onGestureCodeInput(passWordSb.toString());}break;default:break;}return true;}/*** 指定时间去清除绘制的状态* @param delayTime 延迟执行时间*/public void clearDrawlineState(long delayTime) {if (delayTime > 0) {// 绘制红色提示路线isDrawEnable = false;drawErrorPathTip();}new Handler().postDelayed(new clearStateRunnable(), delayTime);}/*** 清除绘制状态的线程*/final class clearStateRunnable implements Runnable {public void run() {// 重置passWordSbpassWordSb = new StringBuilder();// 清空保存点的集合lineList.clear();// 重新绘制界面clearScreenAndDrawList();for (GesturePoint p : list) {p.setPointState(Constants.POINT_STATE_NORMAL);}invalidate();isDrawEnable = true;}}/*** 通过点的位置去集合里面查找这个点是包含在哪个Point里面的** @param x* @param y* @return 如果没有找到,则返回null,代表用户当前移动的地方属于点与点之间*/private GesturePoint getPointAt(int x, int y) {for (GesturePoint point : list) {// 先判断xint leftX = point.getLeftX();int rightX = point.getRightX();if (!(x >= leftX && x < rightX)) {// 如果为假,则跳到下一个对比continue;}int topY = point.getTopY();int bottomY = point.getBottomY();if (!(y >= topY && y < bottomY)) {// 如果为假,则跳到下一个对比continue;}// 如果执行到这,那么说明当前点击的点的位置在遍历到点的位置这个地方return point;}return null;}private GesturePoint getBetweenCheckPoint(GesturePoint pointStart, GesturePoint pointEnd) {int startNum = pointStart.getNum();int endNum = pointEnd.getNum();String key = null;if (startNum < endNum) {key = startNum + "," + endNum;} else {key = endNum + "," + startNum;}return autoCheckPointMap.get(key);}/*** 清掉屏幕上所有的线,然后画出集合里面的线*/private void clearScreenAndDrawList() {canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);for (Pair<GesturePoint, GesturePoint> pair : lineList) {canvas.drawLine(pair.first.getCenterX(), pair.first.getCenterY(),pair.second.getCenterX(), pair.second.getCenterY(), paint);// 画线}}/*** 校验错误/两次绘制不一致提示*/private void drawErrorPathTip() {canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);paint.setColor(Color.rgb(154, 7, 21));// 设置默认线路颜色for (Pair<GesturePoint, GesturePoint> pair : lineList) {pair.first.setPointState(Constants.POINT_STATE_WRONG);pair.second.setPointState(Constants.POINT_STATE_WRONG);canvas.drawLine(pair.first.getCenterX(), pair.first.getCenterY(),pair.second.getCenterX(), pair.second.getCenterY(), paint);// 画线}invalidate();}public interface GestureCallBack {/*** 用户设置/输入了手势密码*/public abstract void onGestureCodeInput(String inputCode);/*** 代表用户绘制的密码与传入的密码相同*/public abstract void checkedSuccess();/*** 代表用户绘制的密码与传入的密码不相同*/public abstract void checkedFail();}}
3,具体的使用 (设置密码之后的使用)
public class GestureVerifyActivity extends Activity implements View.OnClickListener {/** 手机号码*/public static final String PARAM_PHONE_NUMBER = "PARAM_PHONE_NUMBER";/** 意图 */public static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";private RelativeLayout mTopLayout;private TextView mTextTitle;private TextView mTextCancel;private ImageView mImgUserLogo;private TextView mTextPhoneNumber;private TextView mTextTip;private FrameLayout mGestureContainer;private GestureContentView mGestureContentView;private TextView mTextForget;private TextView mTextOther;private String mParamPhoneNumber;private long mExitTime = 0;private int mParamIntentCode;private SharedPreferences mSharedPreferences;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_gesture_verify);ObtainExtraData();setUpViews();setUpListeners();}private void ObtainExtraData() {mParamPhoneNumber = getIntent().getStringExtra(PARAM_PHONE_NUMBER);mParamIntentCode = getIntent().getIntExtra(PARAM_INTENT_CODE, 0);mSharedPreferences = this.getSharedPreferences("secret_protect", Context.MODE_PRIVATE);}private void setUpViews() {mTopLayout = (RelativeLayout) findViewById(R.id.top_layout);mTextTitle = (TextView) findViewById(R.id.text_title);mTextCancel = (TextView) findViewById(R.id.text_cancel);mImgUserLogo = (ImageView) findViewById(R.id.user_logo);mTextPhoneNumber = (TextView) findViewById(R.id.text_phone_number);mTextTip = (TextView) findViewById(R.id.text_tip);mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container);mTextForget = (TextView) findViewById(R.id.text_forget_gesture);mTextOther = (TextView) findViewById(R.id.text_other_account);String inputCode = mSharedPreferences.getString("inputCode","1235789");// 初始化一个显示各个点的viewGroupmGestureContentView = new GestureContentView(this, true, inputCode,new GestureDrawline.GestureCallBack() {@Overridepublic void onGestureCodeInput(String inputCode) {}@Overridepublic void checkedSuccess() {mGestureContentView.clearDrawlineState(0L);Toast.makeText(GestureVerifyActivity.this, "密码正确", Toast.LENGTH_SHORT).show();GestureVerifyActivity.this.finish();}@Overridepublic void checkedFail() {mGestureContentView.clearDrawlineState(1300L);mTextTip.setVisibility(View.VISIBLE);mTextTip.setText(Html.fromHtml("<font color='#c70c1e'>密码错误</font>"));// 左右移动动画Animation shakeAnimation = AnimationUtils.loadAnimation(GestureVerifyActivity.this, R.anim.shake);mTextTip.startAnimation(shakeAnimation);}});// 设置手势解锁显示到哪个布局里面mGestureContentView.setParentView(mGestureContainer);}private void setUpListeners() {mTextCancel.setOnClickListener(this);mTextForget.setOnClickListener(this);mTextOther.setOnClickListener(this);}private String getProtectedMobile(String phoneNumber) {if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() < 11) {return "";}StringBuilder builder = new StringBuilder();builder.append(phoneNumber.subSequence(0,3));builder.append("****");builder.append(phoneNumber.subSequence(7,11));return builder.toString();}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.text_cancel:this.finish();break;default:break;}}}
4)初始化密码时的使用
public class GestureEditActivity extends Activity implements View.OnClickListener {/*** 手机号码*/public static final String PARAM_PHONE_NUMBER = "PARAM_PHONE_NUMBER";/*** 意图*/public static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";/*** 首次提示绘制手势密码,可以选择跳过*/public static final String PARAM_IS_FIRST_ADVICE = "PARAM_IS_FIRST_ADVICE";private TextView mTextTitle;private TextView mTextCancel;private LockIndicator mLockIndicator;private TextView mTextTip;private FrameLayout mGestureContainer;private GestureContentView mGestureContentView;private TextView mTextReset;private String mParamSetUpcode = null;private String mParamPhoneNumber;private boolean mIsFirstInput = true;private String mFirstPassword = null;private String mConfirmPassword = null;private int mParamIntentCode;private SharedPreferences mSharedPreferences = null;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_gesture_edit);setUpViews();setUpListeners();}private void setUpViews() {mTextTitle = (TextView) findViewById(R.id.text_title);mTextCancel = (TextView) findViewById(R.id.text_cancel);mTextReset = (TextView) findViewById(R.id.text_reset);mTextReset.setClickable(false);mLockIndicator = (LockIndicator) findViewById(R.id.lock_indicator);mTextTip = (TextView) findViewById(R.id.text_tip);mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container);mSharedPreferences = this.getSharedPreferences("secret_protect", Context.MODE_PRIVATE);// 初始化一个显示各个点的viewGroupmGestureContentView = new GestureContentView(this, false, "", new GestureDrawline.GestureCallBack() {@Overridepublic void onGestureCodeInput(String inputCode) {if (!isInputPassValidate(inputCode)) {mTextTip.setText(Html.fromHtml("<font color='#c70c1e'>最少链接4个点, 请重新输入</font>"));mGestureContentView.clearDrawlineState(0L);return;}if (mIsFirstInput) {mFirstPassword = inputCode;updateCodeList(inputCode);mGestureContentView.clearDrawlineState(0L);mTextReset.setClickable(true);mTextReset.setText(getString(R.string.reset_gesture_code));} else {if (inputCode.equals(mFirstPassword)) {Toast.makeText(GestureEditActivity.this, "设置成功", Toast.LENGTH_SHORT).show();mGestureContentView.clearDrawlineState(0L);GestureEditActivity.this.finish();} else {mTextTip.setText(Html.fromHtml("<font color='#c70c1e'>与上一次绘制不一致,请重新绘制</font>"));// 左右移动动画Animation shakeAnimation = AnimationUtils.loadAnimation(GestureEditActivity.this, R.anim.shake);mTextTip.startAnimation(shakeAnimation);// 保持绘制的线,1.5秒后清除mGestureContentView.clearDrawlineState(1300L);}}mIsFirstInput = false;}@Overridepublic void checkedSuccess() {}@Overridepublic void checkedFail() {}});// 设置手势解锁显示到哪个布局里面mGestureContentView.setParentView(mGestureContainer);updateCodeList("");}private void setUpListeners() {mTextCancel.setOnClickListener(this);mTextReset.setOnClickListener(this);}private void updateCodeList(String inputCode) {// 更新选择的图案mLockIndicator.setPath(inputCode);mSharedPreferences.edit().putString("inputCode",inputCode).commit();Log.e("TAG", "inputCode = " + inputCode);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.text_cancel:this.finish();break;case R.id.text_reset:mIsFirstInput = true;updateCodeList("");mTextTip.setText(getString(R.string.set_gesture_pattern));break;default:break;}}private boolean isInputPassValidate(String inputPassword) {if (TextUtils.isEmpty(inputPassword) || inputPassword.length() < 4) {return false;}return true;}}
7.项目地址链接:
github:
/wangkuo_123456/gesture_sliding_password_lock.git
csdn:
/download/wk_beicai/11074590