一款简洁可自定义样式密码框输入组件GridPasswordView

通过继承TextView自定义实现的一款密码输入组件GridPasswordView,先上效果图:
一款简洁可自定义样式密码框输入组件GridPasswordView_第1张图片

动态效果图:

这里我根据自己经验做了样式定义与适配适配:

  • 对于一些需求要求每个密码框式正方形也做了适配
  • 支持定义密码框长度,密码可以明文或者密码显示
  • 根据android的inputType类型来确认
  • 增加闪动光标,可自定义样式

只需要在xml中定义显示样式就可以:

UCSGridPasswordView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:cursorVisible="true"
        android:inputType="numberPassword"
        android:padding="8dp"
        android:textSize="18sp"
        app:gpCursorDrawable="@drawable/my_cursor"
        app:gpLineColor="@color/primary"
        app:gpLineHeight="40dp"
        app:gpLineWidth="2dp"
        app:gpPasswordLength="6" />

这里本着开源的精神对源码关键点进行解析:
onMeasure测量方法中测试计算GridPasswordView视图宽高

calLineLayout(int width, int height, int lineWidth)

该方法计算密码框的宽度和高度,以及偏移量
这里其实做了一些处理:由于我是根据定义的密码框高度配合View的宽度来计算密码框X方向 mXLineHeight 的高度,如果配置mXLineHeightFull=true 是充满View,那么我就计算X方向的高度平分View,或者密码框的总宽度超过也是重新计算平分水平方向,此时保证密码框完整显示

计算完相关参数就是在onDraw方法中绘制密码框
唯一需要说的就是光标闪动绘制,这里采用的是局部刷新View的方法,指定刷新光标区域:

        if (mCursorBitmapDrawable != null) {
            mCursorBitmapDrawable.setAlpha(mInvalidateCursorVisible ? 255 : 0);
            if (mCursorRect != null) {
                invalidate(mCursorRect.left, mCursorRect.top, mCursorRect.right, mCursorRect.bottom);
            } else {
                invalidate();
            }
        }
    }

最后附上GitHub下载地址:https://github.com/ttarfall/GridPasswordView
欢迎大家体验使用,如有建议可留言

你可能感兴趣的:(Android)