通過繼承TextView自定義實現的一款密碼輸入組件GridPasswordView,先上效果圖:
動態效果圖:
這裏我根據自己經驗做了樣式定義與適配適配:
- 對於一些需求要求每個密碼框式正方形也做了適配
- 支持定義密碼框長度,密碼可以明文或者密碼顯示
- 根據android的inputType類型來確認
- 增加閃動光標,可自定義樣式
只需要在xml中定義顯示樣式就可以:
<com.ttarfall.gridpassword.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
歡迎大家體驗使用,如有建議可留言