57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android Passcode Keypad View [](https://android-arsenal.com/details/1/4124) [  ](https://bintray.com/arjun-sna/maven/passcodeview/_latestVersion)
2 |
3 | A custom view with keyboard and character display to be used for authentication.
4 |
5 | The view has a bunch customisation options to make to look and work the way whichever needed.
6 |
7 | ## Demo
8 |
9 |
10 |
11 |
12 | ## Installation
13 | Add gradle dependency
14 | ```
15 | repositories {
16 | jcenter()
17 | }
18 | dependencies {
19 | compile 'in.arjsna:passcodeview:1.2.1'
20 | }
21 |
22 | ```
23 |
24 | ## Usage
25 | Add the view in the layout file
26 |
27 | ```xml
28 |
38 |
39 | ```
40 |
41 | View attributes that can be included in xml are
42 |
43 |
44 | `digits` - number of digits in passcode
45 |
46 | `filled_drawable` - drawable to be show for filled digits
47 |
48 | `empty_drawable` - drawable to be show for empty digits
49 |
50 | `key_text_size` - size of text in keyboard's key
51 |
52 | `digit_spacing` - horizontal space between each digit
53 |
54 | `digit_vertical_padding` - vertical padding of digits
55 |
56 | `divider_visible` - boolean to show or hide divider between digits and keyboard
57 |
58 |
59 | Other customisations options available are
60 |
61 | ```java
62 | PassCodeView passCodeView = (PassCodeView) findViewById(R.id.pass_code_view);
63 | Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/Font-Bold.ttf");
64 |
65 | /**
66 | *Set TypeFace for the font in keys of keypad
67 | */
68 | passCodeView.setTypeFace(typeFace);
69 |
70 | /**
71 | * Set color for the keypad text
72 | * @param color - Resource id of the color to be set
73 | */
74 | passCodeView.setKeyTextColor(getResources.getColor(R.color.black));
75 |
76 | /**
77 | * Set size of keypad text
78 | * @param size - Text size value to be set
79 | */
80 | passCodeView.setKeyTextSize(30);
81 |
82 | /**
83 | * Set passcode digit lenght
84 | * @param length - digit length to be set
85 | */
86 | passCodeView.setDigitLength(6);
87 |
88 |
89 | /**
90 | * Set current passcode text
91 | * @param code - {@code String} passcode string to be set
92 | */
93 | public void setPassCode("8854")
94 |
95 | /**
96 | * Reset the code to empty
97 | */
98 | passCodeView.reset();
99 |
100 | /**
101 | * Set drawable for empty digits programmatically
102 | */
103 | passCodeView.setEmptyDrawable(R.drawable.empty);
104 |
105 | /**
106 | * Set drawable for filled digits programmatically
107 | */
108 | passCodeView.setFilledDrawable(R.drawable.filled);
109 |
110 | /**
111 | * Attach {@code TextChangeListener} to get notified on text changes
112 | * @param listener - {@Code TextChangeListener} object to be attached and notified
113 | */
114 | passCodeView.setOnTextChangeListener(new PassCodeView.TextChangeListener() {
115 | @Override
116 | public void onTextChanged(String text) {
117 | Log.i("Passcode", "text");
118 | }
119 | });
120 | ```
121 |
122 |
--------------------------------------------------------------------------------
/passcodeview/src/main/java/in/arjsna/passcodeview/KeyRect.java:
--------------------------------------------------------------------------------
1 | package in.arjsna.passcodeview;
2 |
3 | import android.animation.Animator;
4 | import android.animation.ValueAnimator;
5 | import android.graphics.Rect;
6 | import android.util.Log;
7 | import android.view.View;
8 | import android.view.animation.CycleInterpolator;
9 |
10 | /**
11 | * Created by arjun on 8/3/16.
12 | */
13 | public class KeyRect {
14 | private final View view;
15 | public Rect rect;
16 | public String value;
17 | public int rippleRadius = 0;
18 | public int requiredRadius;
19 | public int circleAlpha;
20 | private final Rect tempRect;
21 | public boolean hasRippleEffect = false;
22 | public ValueAnimator animator;
23 | private final int MAX_RIPPLE_ALPHA = 180;
24 | private InterpolatedValueListener interpolatedValueListener;
25 | private int animationLeftRepeatCount = 2;
26 | private int animationRightRepeatCount = 2;
27 | private int cycleCount = 4;
28 | private RippleAnimListener rippleAnimListener;
29 |
30 | public KeyRect(View view, Rect rect, String value) {
31 | this.view = view;
32 | this.rect = rect;
33 | this.tempRect = new Rect(rect);
34 | this.value = value;
35 | requiredRadius = (this.rect.right - this.rect.left) / 4;
36 | setUpAnimator();
37 | }
38 |
39 | /**
40 | * Initialise the filed and listener for ripple effect animator
41 | */
42 | private void setUpAnimator() {
43 | animator = ValueAnimator.ofFloat(0, requiredRadius);
44 | animator.setDuration(400);
45 | final int circleAlphaOffset = MAX_RIPPLE_ALPHA / requiredRadius;
46 | animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
47 | @Override public void onAnimationUpdate(ValueAnimator animation) {
48 | if (hasRippleEffect) {
49 | float animatedValue = (float) animation.getAnimatedValue();
50 | rippleRadius = (int) animatedValue;
51 | Log.i("Ripple start", "radius " + rippleRadius);
52 | circleAlpha = (int) (MAX_RIPPLE_ALPHA - (animatedValue * circleAlphaOffset));
53 | interpolatedValueListener.onValueUpdated();
54 | }
55 | }
56 | });
57 |
58 | animator.addListener(new ValueAnimator.AnimatorListener() {
59 | @Override public void onAnimationStart(Animator animation) {
60 | hasRippleEffect = true;
61 | }
62 |
63 | @Override public void onAnimationEnd(Animator animation) {
64 | hasRippleEffect = false;
65 | rippleRadius = 0;
66 | rippleAnimListener.onEnd();
67 | }
68 |
69 | @Override public void onAnimationCancel(Animator animation) {
70 |
71 | }
72 |
73 | @Override public void onAnimationRepeat(Animator animation) {
74 |
75 | }
76 | });
77 | }
78 |
79 | /**
80 | * Set the valued of this Key
81 | *
82 | * @param value - Value to be set for this key
83 | */
84 | public void setValue(String value) {
85 | this.value = value;
86 | }
87 |
88 | /**
89 | * Show animation indicated invalid pincode
90 | */
91 | public void setError() {
92 | ValueAnimator goLeftAnimator = ValueAnimator.ofInt(0, 5);
93 | goLeftAnimator.setInterpolator(new CycleInterpolator(2));
94 | goLeftAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
95 | @Override public void onAnimationUpdate(ValueAnimator animation) {
96 | rect.left += (int) animation.getAnimatedValue();
97 | rect.right += (int) animation.getAnimatedValue();
98 | view.invalidate();
99 | }
100 | });
101 | goLeftAnimator.start();
102 | }
103 |
104 | public interface InterpolatedValueListener {
105 | void onValueUpdated();
106 | }
107 |
108 | public void setOnValueUpdateListener(InterpolatedValueListener listener) {
109 | this.interpolatedValueListener = listener;
110 | }
111 |
112 | /**
113 | * Start Playing ripple animation and notify listener accordingly
114 | *
115 | * @param listener - {@link in.arjsna.passcodeview.KeyRect.RippleAnimListener} object to be
116 | * notified
117 | */
118 | public void playRippleAnim(RippleAnimListener listener) {
119 | this.rippleAnimListener = listener;
120 | setOnValueUpdateListener(new KeyRect.InterpolatedValueListener() {
121 | @Override public void onValueUpdated() {
122 | view.invalidate(rect);
123 | }
124 | });
125 | rippleAnimListener.onStart();
126 | animator.start();
127 | }
128 |
129 | /**
130 | * Interface to get notified on ripple animation status
131 | */
132 | public interface RippleAnimListener {
133 | void onStart();
134 |
135 | void onEnd();
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/passcodeview/src/main/java/in/arjsna/passcodeview/PassCodeView.java:
--------------------------------------------------------------------------------
1 | package in.arjsna.passcodeview;
2 |
3 | import android.annotation.TargetApi;
4 | import android.content.Context;
5 | import android.content.res.ColorStateList;
6 | import android.content.res.TypedArray;
7 | import android.graphics.Bitmap;
8 | import android.graphics.Canvas;
9 | import android.graphics.Color;
10 | import android.graphics.Paint;
11 | import android.graphics.Rect;
12 | import android.graphics.Typeface;
13 | import android.graphics.drawable.Drawable;
14 | import android.text.TextPaint;
15 | import android.util.AttributeSet;
16 | import android.util.Log;
17 | import android.view.MotionEvent;
18 | import android.view.View;
19 |
20 | import java.util.ArrayList;
21 | import java.util.HashMap;
22 | import java.util.Map;
23 |
24 | /**
25 | * Created by arjun on 8/2/16.
26 | */
27 | public class PassCodeView extends View {
28 | private boolean DEBUG = false;
29 | private final int KEYS_COUNT = 12;
30 | private final String eraseChar = "\u232B";
31 | private final int KEY_PAD_COLS = 3;
32 | private final int KEY_PAD_ROWS = 4;
33 | private int digits;
34 | private int filledCount = 0;
35 | private Bitmap filledDrawable;
36 | private Bitmap emptyDrawable;
37 | private Paint paint;
38 | private int DEFAULT_DRAWABLE_DIM;
39 | private int DEFAULT_VIEW_HEIGHT = 200;
40 | private int digitVerticalPadding;
41 | private int drawableWidth;
42 | private int drawableHeight;
43 | private int drawableStartX;
44 | private int drawableStartY;
45 | private int digitHorizontalPadding;
46 | private int kpStartX;
47 | private int kpStartY;
48 | private ArrayList keyRects = new ArrayList<>();
49 | private int keyWidth;
50 | private int keyHeight;
51 | private String passCodeText = "";
52 | private TextChangeListener textChangeListener;
53 | private boolean skipKeyDraw = false;
54 | private int touchSlope = 5;
55 |
56 | private Map touchXMap = new HashMap<>();
57 | private Map touchYMap = new HashMap<>();
58 | private Typeface typeFace;
59 | private TextPaint textPaint;
60 | private float keyTextSize;
61 | private long animDuration = 200;
62 | private Paint circlePaint;
63 |
64 | private boolean dividerVisible;
65 | private float dividerStartX;
66 | private float dividerStartY;
67 | private float dividerEndX;
68 | private float dividerEndY;
69 | private Context context;
70 |
71 | public PassCodeView(Context context) {
72 | super(context);
73 | init(context, null, 0, 0);
74 | }
75 |
76 | public PassCodeView(Context context, AttributeSet attrs) {
77 | super(context, attrs);
78 | init(context, attrs, 0, 0);
79 | }
80 |
81 | public PassCodeView(Context context, AttributeSet attrs, int defStyleAttr) {
82 | super(context, attrs, defStyleAttr);
83 | init(context, attrs, defStyleAttr, 0);
84 | }
85 |
86 | @TargetApi(21)
87 | public PassCodeView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
88 | super(context, attrs, defStyleAttr, defStyleRes);
89 | init(context, attrs, defStyleAttr, defStyleRes);
90 | }
91 |
92 | private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
93 | this.context = context;
94 | TypedArray values = context.getTheme()
95 | .obtainStyledAttributes(attrs, R.styleable.PassCodeView, defStyleAttr, defStyleRes);
96 | try {
97 | digits = values.getInteger(R.styleable.PassCodeView_digits, 4);
98 | float digitSize = values.getDimension(R.styleable.PassCodeView_digit_size,
99 | getResources().getDimension(R.dimen.drawableDimen));
100 | keyTextSize = values.getDimension(R.styleable.PassCodeView_key_text_size,
101 | getResources().getDimension(R.dimen.key_text_size));
102 | dividerVisible = values.getBoolean(R.styleable.PassCodeView_divider_visible, true);
103 | digitHorizontalPadding = (int) values.getDimension(R.styleable.PassCodeView_digit_spacing,
104 | getResources().getDimension(R.dimen.digit_horizontal_padding));
105 | digitVerticalPadding =
106 | (int) values.getDimension(R.styleable.PassCodeView_digit_vertical_padding,
107 | getResources().getDimension(R.dimen.digit_vertical_padding));
108 |
109 | drawableWidth = (int) digitSize; //DEFAULT_DRAWABLE_DIM;
110 | drawableHeight = (int) digitSize; //DEFAULT_DRAWABLE_DIM;
111 | setFilledDrawable(values.getResourceId(R.styleable.PassCodeView_filled_drawable, -1));
112 | setEmptyDrawable(values.getResourceId(R.styleable.PassCodeView_empty_drawable, -1));
113 | } catch (Exception e) {
114 | e.printStackTrace();
115 | }
116 | values.recycle();
117 | preparePaint();
118 | }
119 |
120 | private void preparePaint() {
121 | paint = new Paint(TextPaint.ANTI_ALIAS_FLAG);
122 | textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
123 | circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
124 | circlePaint.setStyle(Paint.Style.FILL);
125 | paint.setStyle(Paint.Style.FILL);
126 | textPaint.setStyle(Paint.Style.FILL);
127 | textPaint.setColor(Color.argb(255, 0, 0, 0));
128 | textPaint.density = getResources().getDisplayMetrics().density;
129 | textPaint.setTextSize(keyTextSize);
130 | textPaint.setTextAlign(Paint.Align.CENTER);
131 | }
132 |
133 | public void setTypeFace(Typeface typeFace) {
134 | if (this.typeFace != typeFace) {
135 | this.typeFace = typeFace;
136 | textPaint.setTypeface(typeFace);
137 | requestLayout();
138 | invalidate();
139 | }
140 | }
141 |
142 | /**
143 | * Set color for the keypad text
144 | *
145 | * @param color - Resource id of the color to be set
146 | */
147 | public void setKeyTextColor(int color) {
148 | ColorStateList colorStateList = ColorStateList.valueOf(color);
149 | textPaint.setColor(colorStateList.getColorForState(getDrawableState(), 0));
150 | invalidate();
151 | }
152 |
153 | /**
154 | * Set size of keypad text
155 | *
156 | * @param size - Text size value to be set
157 | */
158 | public void setKeyTextSize(float size) {
159 | textPaint.setTextSize(size);
160 | requestLayout();
161 | invalidate();
162 | }
163 |
164 | /**
165 | * Compute the start point(x, y) to draw drawables showing filled and empty
166 | * pin code digits.
167 | */
168 | private void computeDrawableStartXY() {
169 | int totalDrawableWidth = digits * drawableWidth;
170 | int totalPaddingWidth = digitHorizontalPadding * (digits - 1);
171 | int totalReqWidth = totalDrawableWidth + totalPaddingWidth;
172 | drawableStartX = getMeasuredWidth() / 2 - totalReqWidth / 2;
173 | drawableStartY = (drawableHeight + digitVerticalPadding) / 2 - drawableHeight / 2;
174 | computeKeyboardStartXY();
175 | }
176 |
177 | /**
178 | * Compute the start point(x, y) to draw keyboard keys
179 | */
180 | private void computeKeyboardStartXY() {
181 | kpStartX = 0;
182 | kpStartY = drawableHeight + digitVerticalPadding;
183 | keyWidth = getMeasuredWidth() / KEY_PAD_COLS;
184 | keyHeight = (getMeasuredHeight() - (drawableHeight + digitVerticalPadding)) / KEY_PAD_ROWS;
185 | initialiseKeyRects();
186 | if (dividerVisible) {
187 | computeDividerPos();
188 | }
189 | }
190 |
191 | private void computeDividerPos() {
192 | float widthFactor = 10;
193 | dividerStartX = keyWidth / 2 - widthFactor;
194 | dividerStartY = drawableHeight + digitVerticalPadding;
195 | dividerEndX = (getMeasuredWidth() - keyWidth / 2) + widthFactor;
196 | dividerEndY = dividerStartY;
197 | }
198 |
199 | /**
200 | * Initialise a {@link KeyRect} for each key in keyboard which holds details
201 | * of key like position, value etc.
202 | */
203 | private void initialiseKeyRects() {
204 | keyRects.clear();
205 | int x = kpStartX, y = kpStartY;
206 | for (int i = 1; i <= KEYS_COUNT; i++) {
207 | keyRects.add(
208 | new KeyRect(this, new Rect(x, y, x + keyWidth, y + keyHeight), String.valueOf(i)));
209 | x = x + keyWidth;
210 | if (i % 3 == 0) {
211 | y = y + keyHeight;
212 | x = kpStartX;
213 | }
214 | }
215 | keyRects.get(9).setValue("");
216 | keyRects.get(10).setValue("0");
217 | keyRects.get(11).setValue(eraseChar);
218 | }
219 |
220 | /**
221 | * Create a {@link Bitmap} for the given @param resId
222 | *
223 | * @param resId - The resource id of the drawable for which the bitmap should be
224 | * created
225 | * @return {@link Bitmap} of the drawable whose resource id is passed in
226 | */
227 | private Bitmap getBitmap(int resId) {
228 | Drawable drawable = getResources().getDrawable(resId);
229 | Canvas canvas = new Canvas();
230 | Bitmap bitmap = Bitmap.createBitmap(drawableWidth, drawableHeight, Bitmap.Config.ARGB_8888);
231 | canvas.setBitmap(bitmap);
232 | drawable.setBounds(0, 0, drawableWidth, drawableHeight);
233 | drawable.draw(canvas);
234 | return bitmap;
235 | }
236 |
237 | @Override protected void onDraw(Canvas canvas) {
238 | super.onDraw(canvas);
239 | drawDigitDrawable(canvas);
240 | if (dividerVisible) {
241 | drawDivider(canvas);
242 | }
243 | drawKeyPad(canvas);
244 | }
245 |
246 | private void drawDivider(Canvas canvas) {
247 | paint.setAlpha(40);
248 | canvas.drawLine(dividerStartX, dividerStartY, dividerEndX, dividerEndY, paint);
249 | }
250 |
251 | /**
252 | * Draw the keys of keypad on the canvas starting from the previously computed start
253 | * point if keyboard
254 | *
255 | * @param canvas - {@link Canvas} on which the keypad should be drawn
256 | */
257 | private void drawKeyPad(Canvas canvas) {
258 | float centerHalf = (textPaint.descent() + textPaint.ascent()) / 2;
259 | for (KeyRect rect : keyRects) {
260 | canvas.drawText(rect.value, rect.rect.exactCenterX(), rect.rect.exactCenterY() - centerHalf,
261 | textPaint);
262 | if (rect.hasRippleEffect) {
263 | circlePaint.setAlpha(rect.circleAlpha);
264 | canvas.drawCircle(rect.rect.exactCenterX(), rect.rect.exactCenterY(), rect.rippleRadius,
265 | circlePaint);
266 | }
267 | if (DEBUG) {
268 | canvas.drawLine(rect.rect.left, rect.rect.centerY(), rect.rect.right, rect.rect.centerY(),
269 | textPaint);
270 | canvas.drawLine(rect.rect.centerX(), rect.rect.top, rect.rect.centerX(), rect.rect.bottom,
271 | textPaint);
272 | canvas.drawRect(rect.rect, textPaint);
273 | }
274 | }
275 | }
276 |
277 | /**
278 | * Draw the {@link Bitmap} of the drawable which indicated filled and empty
279 | * passcode digits
280 | *
281 | * @param canvas - {@link Canvas} on which the drawable should be drawn
282 | */
283 | private void drawDigitDrawable(Canvas canvas) {
284 | paint.setAlpha(255);
285 | int x = drawableStartX, y = drawableStartY;
286 | int totalContentWidth = drawableWidth + digitHorizontalPadding;
287 | for (int i = 1; i <= filledCount; i++) {
288 | canvas.drawBitmap(filledDrawable, x, y, paint);
289 | x += totalContentWidth;
290 | }
291 | for (int i = 1; i <= (digits - filledCount); i++) {
292 | canvas.drawBitmap(emptyDrawable, x, y, paint);
293 | x += totalContentWidth;
294 | }
295 | }
296 |
297 | @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
298 | int widthMode = MeasureSpec.getMode(widthMeasureSpec);
299 | int heightMode = MeasureSpec.getMode(heightMeasureSpec);
300 | int paddingLeft = getPaddingLeft();
301 | int paddingRight = getPaddingRight();
302 | int paddingTop = getPaddingTop();
303 | int paddingBottom = getPaddingBottom();
304 | int measuredWidth = 0, measuredHeight = 0;
305 | if (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST) {
306 | measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
307 | }
308 |
309 | if (heightMode == MeasureSpec.EXACTLY) {
310 | measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
311 | } else if (heightMode == MeasureSpec.AT_MOST) {
312 | double height = MeasureSpec.getSize(heightMeasureSpec) * 0.8;
313 | measuredHeight = (int) height;// + paddingTop + paddingBottom;
314 | }
315 | measuredHeight =
316 | (int) Math.max(measuredHeight, getResources().getDimension(R.dimen.key_pad_min_height));
317 | setMeasuredDimension(measuredWidth, measuredHeight);
318 | computeDrawableStartXY();
319 | }
320 |
321 | /**
322 | * Set the count of digits entered by user
323 | *
324 | * @param count - {@link int} value of the digits filled
325 | */
326 | private void setFilledCount(int count) {
327 | filledCount = count > digits ? digits : count;
328 | /*invalidate(drawableStartX,
329 | drawableStartX,
330 | drawableStartX + getMeasuredWidth(),
331 | drawableStartY + getMeasuredHeight());*/
332 | /* The coordinates passed to `invalidate` method above is wrong
333 | which makes the View not be drawn correctly
334 | hence calling the default invalidate method */
335 | invalidate();
336 | }
337 |
338 | @Override public boolean onTouchEvent(MotionEvent event) {
339 | return processTouch(event);
340 | }
341 |
342 | /**
343 | * Process the {@link MotionEvent} and detect the key pressed and perform
344 | * appropriate action
345 | *
346 | * @param event - {@link MotionEvent} triggered by user action
347 | * @return {code boolean} whether event is consumed or not
348 | */
349 | private boolean processTouch(MotionEvent event) {
350 | switch (event.getActionMasked()) {
351 | case MotionEvent.ACTION_DOWN:
352 | int pointerDownId = event.getPointerId(event.getActionIndex());
353 | touchXMap.put(pointerDownId, (int) event.getX());
354 | touchYMap.put(pointerDownId, (int) event.getY());
355 | break;
356 |
357 | case MotionEvent.ACTION_UP:
358 | int pointerUpId = event.getPointerId(event.getActionIndex());
359 | int pointerUpIndex = event.findPointerIndex(pointerUpId);
360 | int eventX = (int) event.getX(pointerUpIndex);
361 | int eventY = (int) event.getY(pointerUpIndex);
362 | findKeyPressed(touchXMap.get(pointerUpId), touchYMap.get(pointerUpId), eventX, eventY);
363 | break;
364 |
365 | case MotionEvent.ACTION_POINTER_DOWN:
366 | Log.i("Pointer", "down");
367 | int pointerActionDownId = event.getPointerId(event.getActionIndex());
368 | touchXMap.put(pointerActionDownId, (int) event.getX(event.getActionIndex()));
369 | touchYMap.put(pointerActionDownId, (int) event.getY(event.getActionIndex()));
370 | break;
371 |
372 | case MotionEvent.ACTION_POINTER_UP:
373 | int pointerActionUpIndex = event.getActionIndex();
374 | int pointerActionUpId = event.getPointerId(pointerActionUpIndex);
375 | int eventPointerX = (int) event.getX(pointerActionUpIndex);
376 | int eventPointerY = (int) event.getY(pointerActionUpIndex);
377 | findKeyPressed(touchXMap.get(pointerActionUpId), touchYMap.get(pointerActionUpId),
378 | eventPointerX, eventPointerY);
379 | break;
380 |
381 | case MotionEvent.ACTION_MOVE:
382 | case MotionEvent.ACTION_CANCEL:
383 | return false;
384 | }
385 | return true;
386 | }
387 |
388 | /**
389 | * Find the key which is pressed by find the {@link Rect} which container the
390 | * passed in touch event points
391 | *
392 | * @param downEventX - X co-ordinate of the pointer down event
393 | * @param downEventY - Y co-ordinate of the pointer down event
394 | * @param upEventX - X co-ordinate of the pointer up event
395 | * @param upEventY - Y co-ordinate of the pointer up event
396 | */
397 | private void findKeyPressed(int downEventX, int downEventY, int upEventX, int upEventY) {
398 | for (final KeyRect keyRect : keyRects) {
399 | if (keyRect.rect.contains(downEventX, downEventY) && keyRect.rect.contains(upEventX,
400 | upEventY)) {
401 | keyRect.playRippleAnim(new KeyRect.RippleAnimListener() {
402 | @Override public void onStart() {
403 | int length = passCodeText.length();
404 | if (keyRect.value.equals(eraseChar)) {
405 | if (length > 0) {
406 | passCodeText = passCodeText.substring(0, passCodeText.length() - 1);
407 | setFilledCount(passCodeText.length());
408 | }
409 | } else if (!keyRect.value.isEmpty() && length < digits) {
410 | passCodeText = passCodeText + keyRect.value;
411 | setFilledCount(passCodeText.length());
412 | }
413 | }
414 |
415 | @Override public void onEnd() {
416 | if (!keyRect.value.isEmpty()) {
417 | notifyListener();
418 | }
419 | }
420 | });
421 | }
422 | }
423 | }
424 |
425 | public void setEmptyDrawable(int resId) {
426 | emptyDrawable = getBitmap(resId);
427 | }
428 |
429 |
430 | public void setFilledDrawable(int resId) {
431 | filledDrawable = getBitmap(resId);
432 | }
433 |
434 | /**
435 | * Reset the code to empty and redraw the view
436 | */
437 | public void reset() {
438 | this.passCodeText = "";
439 | invalidateAndNotifyListener();
440 | }
441 |
442 | /**
443 | * Interface to get notified on text change
444 | */
445 | public interface TextChangeListener {
446 | void onTextChanged(String text);
447 | }
448 |
449 | /**
450 | * Set the filled count of the passcode view and
451 | * redraw based on the new value and notify the
452 | * attached listener of the change
453 | */
454 | private void invalidateAndNotifyListener() {
455 | setFilledCount(passCodeText.length());
456 | Log.i("New text", passCodeText);
457 | if (textChangeListener != null) {
458 | textChangeListener.onTextChanged(passCodeText);
459 | }
460 | }
461 |
462 | private void notifyListener() {
463 | if (textChangeListener != null) {
464 | textChangeListener.onTextChanged(passCodeText);
465 | }
466 | }
467 |
468 | /**
469 | * Attach {@link TextChangeListener} to get notified on text changes
470 | *
471 | * @param listener - {@link TextChangeListener} object to be attached and notified
472 | */
473 | public void setOnTextChangeListener(TextChangeListener listener) {
474 | this.textChangeListener = listener;
475 | }
476 |
477 | /**
478 | * Remove the attached {@code TextChangeListener}
479 | */
480 | public void removeOnTextChangeListener() {
481 | this.textChangeListener = null;
482 | }
483 |
484 | /**
485 | * Show error feedback to the user
486 | *
487 | * @param reset - {@code boolean} value whether to reset the pass code before showing
488 | * error feedback
489 | */
490 | public void setError(boolean reset) {
491 | if (reset) {
492 | reset();
493 | }
494 | for (KeyRect keyRect : keyRects) {
495 | keyRect.setError();
496 | }
497 | }
498 |
499 | /**
500 | * Set passcode digit length
501 | *
502 | * @param length - {@code int} digit length to be set
503 | */
504 | public void setDigitLength(int length) {
505 | this.digits = length;
506 | invalidate();
507 | }
508 |
509 | /**
510 | * get digit length
511 | *
512 | * @return - {@code int} current length of passcode
513 | */
514 | public int getDigitLength() {
515 | return digits;
516 | }
517 |
518 | /**
519 | * Set current passcode text
520 | *
521 | * @param code - {@code String} passcode string to be set
522 | */
523 | public void setPassCode(String code) {
524 | this.passCodeText = code;
525 | setFilledCount(code.length());
526 | invalidate();
527 | }
528 |
529 | /**
530 | * Get current passcode entered
531 | *
532 | * @return - {@code String} current passcode entered
533 | */
534 | public String getPassCodeText() {
535 | return passCodeText;
536 | }
537 | }
538 |
--------------------------------------------------------------------------------