PinField.kt 12.3 KB
Newer Older
霍志良 committed
1 2 3 4 5 6
package com.yidianling.user.widget.PinField
import `in`.srain.cube.util.LocalDisplay.dp2px
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
YKai committed
7 8
import androidx.core.content.ContextCompat
import androidx.appcompat.widget.AppCompatEditText
霍志良 committed
9 10 11 12 13 14
import android.text.InputFilter
import android.text.method.PasswordTransformationMethod
import android.text.method.TransformationMethod
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
霍志良 committed
15
import com.yidianling.common.tools.LogUtil
霍志良 committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
import com.yidianling.user.R


/**
 * Created by poovam-5255 on 3/3/2018.
 * View where all the magic happens
 */
open class PinField : AppCompatEditText {

    private val defaultWidth = dp2px(60f)

    companion object {
        const val DEFAULT_DISTANCE_IN_BETWEEN = -1f
    }

    protected var distanceInBetween: Float =
        DEFAULT_DISTANCE_IN_BETWEEN
        set(value) {
            field = value
            requestLayout()
            invalidate()
        }

    var numberOfFields = 4
        set(value) {
            field = value
            limitCharsToNoOfFields()
            invalidate()
        }

    protected var singleFieldWidth = 0
    var lineThickness = dp2px(1.0f)
        set(value) {
            field = value
            fieldPaint.strokeWidth = field.toFloat()
            highlightPaint.strokeWidth = highLightThickness.toFloat()
            invalidate()
        }

    var fieldColor = ContextCompat.getColor(context, R.color.user_inactivePinFieldColor)
        set(value) {
            field = value
            fieldPaint.color = field
            invalidate()
        }

    var highlightPaintColor = ContextCompat.getColor(context, R.color.user_pinFieldLibraryAccent)
        set(value) {
            field = value
            highlightPaint.color = field
            invalidate()
        }

    var isCursorEnabled = false
        set(value) {
            field = value
            invalidate()
        }

    protected var fieldPaint = Paint()

    protected var textPaint = Paint()

    protected var hintPaint = Paint()

    protected var highlightPaint = Paint()

    protected var yPadding = dp2px(10f)

霍志良 committed
85
    var highlightSingleFieldType =
霍志良 committed
86 87 88 89 90 91 92
        HighlightType.ALL_FIELDS

    private var lastCursorChangeState: Long = -1

    private var cursorCurrentVisible = true

    private val cursorTimeout = 500L
霍志良 committed
93
//    public var fieldBgColor=0
霍志良 committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    var isCustomBackground = false
        set(value) {
            if (!value) {
                setBackgroundResource(R.color.user_pinFieldLibraryTransparent)
            }
            field = value
        }

    var highLightThickness = lineThickness
        get() {
            return (lineThickness + lineThickness * 0.7f).toInt()
        }

    var onTextCompleteListener: OnTextCompleteListener? = null

    var fieldBgColor = ContextCompat.getColor(context, R.color.user_pinFieldLibraryAccent)
        set(value) {
            field = value
            fieldBgPaint.color = fieldBgColor
            invalidate()
        }

    var fieldBgPaint = Paint()

    init {
        limitCharsToNoOfFields()
        setWillNotDraw(false)
        maxLines = 1
        setSingleLine(true)

        fieldPaint.color = fieldColor
        fieldPaint.isAntiAlias = true
        fieldPaint.style = Paint.Style.STROKE
        fieldPaint.strokeWidth = lineThickness.toFloat()

        textPaint.color = currentTextColor
        textPaint.isAntiAlias = true
        textPaint.textSize = textSize
        textPaint.textAlign = Paint.Align.CENTER
        textPaint.style = Paint.Style.FILL

        hintPaint.color = hintTextColors.defaultColor
        hintPaint.isAntiAlias = true
        hintPaint.textSize = textSize
        hintPaint.textAlign = Paint.Align.CENTER
        hintPaint.style = Paint.Style.FILL

        highlightPaint = Paint(fieldPaint)
        highlightPaint.color = highlightPaintColor
        highlightPaint.strokeWidth = highLightThickness.toFloat()
        fieldBgColor = Color.TRANSPARENT
        fieldBgPaint.style = Paint.Style.FILL
    }

    constructor(context: Context) : super(context)

    constructor(context: Context, attr: AttributeSet) : super(context, attr) {
        initParams(attr)
    }

    constructor(context: Context, attr: AttributeSet, defStyle: Int) : super(
        context,
        attr,
        defStyle
    ) {
        initParams(attr)
    }

    private fun initParams(attr: AttributeSet) {
        val a = context.theme.obtainStyledAttributes(attr, R.styleable.User_PinField, 0, 0)

        try {
            numberOfFields = a.getInt(R.styleable.User_PinField_User_noOfFields, numberOfFields)
            lineThickness =
                a.getDimension(R.styleable.User_PinField_User_lineThickness, lineThickness.toFloat()).toInt()
            distanceInBetween = a.getDimension(
                R.styleable.User_PinField_User_distanceInBetween,
                DEFAULT_DISTANCE_IN_BETWEEN
            )
            fieldColor = a.getColor(R.styleable.User_PinField_User_fieldColor, fieldColor)
            highlightPaintColor =
                a.getColor(R.styleable.User_PinField_User_highlightColor, highlightPaintColor)
            isCustomBackground = a.getBoolean(R.styleable.User_PinField_User_isCustomBackground, false)
            isCursorEnabled = a.getBoolean(R.styleable.User_PinField_User_isCursorEnabled, false)
            highlightSingleFieldType = if (a.getBoolean(
                    R.styleable.User_PinField_User_highlightEnabled,
                    true
                )
            ) HighlightType.ALL_FIELDS else HighlightType.NO_FIELDS
            highlightSingleFieldType = if (a.getBoolean(
                    R.styleable.User_PinField_User_highlightSingleFieldMode,
                    false
                )
            ) HighlightType.CURRENT_FIELD else HighlightType.ALL_FIELDS
            highlightSingleFieldType =
                HighlightType.getEnum(
霍志良 committed
190 191 192 193
                    a.getInt(
                        R.styleable.User_PinField_User_highlightType,
                        highlightSingleFieldType.code
                    )
霍志良 committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
                )
            fieldBgColor = a.getColor(R.styleable.User_PinField_User_fieldBgColor, fieldBgColor)
            textPaint.typeface = typeface
        } finally {
            a.recycle()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = getViewWidth(defaultWidth * numberOfFields, widthMeasureSpec)
        singleFieldWidth = width / numberOfFields
        setMeasuredDimension(width, getViewHeight(singleFieldWidth, heightMeasureSpec))
    }

    protected open fun getViewWidth(desiredWidth: Int, widthMeasureSpec: Int): Int {
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)

        //Measure Width
        return when (widthMode) {
            MeasureSpec.EXACTLY -> widthSize
            MeasureSpec.AT_MOST -> Math.min(desiredWidth, widthSize)
            MeasureSpec.UNSPECIFIED -> desiredWidth
            else -> desiredWidth
        }
    }

    protected open fun getViewHeight(desiredHeight: Int, heightMeasureSpec: Int): Int {
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)

        //Measure Height
        return when (heightMode) {
            MeasureSpec.EXACTLY -> heightSize
            MeasureSpec.AT_MOST -> Math.min(desiredHeight, heightSize)
            MeasureSpec.UNSPECIFIED -> desiredHeight
            else -> desiredHeight
        }
    }

    override fun onSelectionChanged(selStart: Int, selEnd: Int) {
        this.setSelection(this.text!!.length)
    }

    final override fun setWillNotDraw(willNotDraw: Boolean) {
        super.setWillNotDraw(willNotDraw)
    }

    override fun onCheckIsTextEditor(): Boolean {
        return true
    }

    protected open fun getDefaultDistanceInBetween(): Float {
        return (singleFieldWidth / (numberOfFields - 1)).toFloat()
    }

    private fun limitCharsToNoOfFields() {
        val filterArray = arrayOfNulls<InputFilter>(1)
        filterArray[0] = InputFilter.LengthFilter(numberOfFields)
        filters = filterArray
    }

    override fun onTextChanged(
        text: CharSequence?,
        start: Int,
        lengthBefore: Int,
        lengthAfter: Int
    ) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        if (text != null && text.length == numberOfFields) {
            val shouldCloseKeyboard = onTextCompleteListener?.onTextComplete(text.toString())
                ?: false
            if (shouldCloseKeyboard) {
                val imm =
                    context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(windowToken, 0)
            }
        }
    }

    protected fun shouldDrawHint(): Boolean {
        return (text!!.isEmpty() || text!!.isBlank()) &&
                !isFocused && (hint != null && hint.isNotBlank() && hint.isNotEmpty())
    }

    protected fun drawCursor(canvas: Canvas?, x: Float, y1: Float, y2: Float, paint: Paint) {
        if (System.currentTimeMillis() - lastCursorChangeState > 500) {
            cursorCurrentVisible = !cursorCurrentVisible
            lastCursorChangeState = System.currentTimeMillis()
        }

        if (cursorCurrentVisible) {
            canvas?.drawLine(x, y1, x, y2, paint)
        }

        postInvalidateDelayed(cursorTimeout)
    }

    final override fun setBackgroundResource(resId: Int) {
        super.setBackgroundResource(resId)
    }

    protected fun highlightNextField(): Boolean {
        return highlightSingleFieldType == HighlightType.CURRENT_FIELD
    }

    protected fun highlightCompletedFields(): Boolean {
        return highlightSingleFieldType == HighlightType.COMPLETED_FIELDS
    }

    protected fun highlightAllFields(): Boolean {
        return highlightSingleFieldType == HighlightType.ALL_FIELDS
    }

    protected fun highlightNoFields(): Boolean {
        return highlightSingleFieldType == HighlightType.NO_FIELDS
    }

    protected fun highlightLogic(currentPosition: Int, textLength: Int?, onHighlight: () -> Unit) {
        if (hasFocus() && !highlightNoFields()) {
            when {
                highlightNextField() && currentPosition == textLength ?: 0 -> {
                    onHighlight.invoke()
                }
                highlightCompletedFields() && currentPosition < textLength ?: 0 -> {
                    onHighlight.invoke()
                }
            }
        }
    }

    //There is a issue where android transformation method is not set to password so as a work around
    //the transformation method used is hardcoded
    //the check condition used in isPassword() is taken from TextView.java constructor
    protected fun getCharAt(i: Int): Char? {
        return getPinFieldTransformation().getTransformation(text, this)?.getOrNull(i)
            ?: text?.getOrNull(i)
    }

    private fun getPinFieldTransformation(): TransformationMethod {
        if (isPassword()) {
            return PasswordTransformationMethod.getInstance()
        }

        return transformationMethod
    }

    private fun isPassword(): Boolean {
        val variation = inputType and (EditorInfo.TYPE_MASK_CLASS or EditorInfo.TYPE_MASK_VARIATION)
        val passwordInputType = (variation
                == EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)
        val webPasswordInputType = (variation
                == EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD)
        val numberPasswordInputType = (variation
                == EditorInfo.TYPE_CLASS_NUMBER or EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD)

        return passwordInputType || webPasswordInputType
                || numberPasswordInputType
    }

    interface OnTextCompleteListener {
        /**
         * @return return true if keyboard should be closed after text is entered
         */
        fun onTextComplete(enteredText: String): Boolean
    }
}

enum class HighlightType(val code: Int) {
    ALL_FIELDS(0), CURRENT_FIELD(1), COMPLETED_FIELDS(2), NO_FIELDS(3);

    companion object {
        fun getEnum(code: Int): HighlightType {
            for (type in HighlightType.values()) {
                if (type.code == code) {
                    return type
                }
            }
            return ALL_FIELDS
        }
    }
}