├── sampleapp
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── dimens.xml
│ │ │ └── strings.xml
│ │ └── layout
│ │ │ └── activity_main.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── azimolabs
│ │ └── maskformatter
│ │ └── sampleapp
│ │ └── MainActivity.java
├── proguard-rules.pro
└── build.gradle
├── maskformatter
├── .gitignore
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── azimolabs
│ │ │ └── maskformatter
│ │ │ ├── InvalidTextException.java
│ │ │ ├── CharInputType.java
│ │ │ ├── CharTransforms.java
│ │ │ └── MaskFormatter.java
│ └── test
│ │ └── java
│ │ └── com
│ │ └── azimolabs
│ │ └── maskformatter
│ │ ├── CharTransformsTests.java
│ │ └── MaskFormatterTests.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── art
├── animated.gif
└── screenshot.png
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── gradle-bintray-push.gradle
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── README.md
├── gradlew
└── LICENSE
/sampleapp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/maskformatter/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':maskformatter', ':sampleapp'
2 |
--------------------------------------------------------------------------------
/art/animated.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AzimoLabs/MaskFormatter/HEAD/art/animated.gif
--------------------------------------------------------------------------------
/art/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AzimoLabs/MaskFormatter/HEAD/art/screenshot.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AzimoLabs/MaskFormatter/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/maskformatter/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/sampleapp/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 8dp
5 |
6 |
--------------------------------------------------------------------------------
/maskformatter/src/main/java/com/azimolabs/maskformatter/InvalidTextException.java:
--------------------------------------------------------------------------------
1 | package com.azimolabs.maskformatter;
2 |
3 | /**
4 | * Created by maciek on 16.03.2016.
5 | */
6 | public class InvalidTextException extends Exception {
7 | }
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
7 |
--------------------------------------------------------------------------------
/sampleapp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | sampleapp
3 |
4 | Field with mask: AA 9999 AAAA wwww wwww wwww
5 | Field with mask: dd DD 1234 5678 90
6 | Field with mask: AAZZ aazz @@ww ##%%
7 | Password field with mask: 999 99 9999
8 | Field with mask: 999–999–9999
9 |
10 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 | .idea
5 |
6 | # Files for the Dalvik VM
7 | *.dex
8 |
9 | # Java class files
10 | *.class
11 |
12 | # Generated files
13 | bin/
14 | gen/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | .DS_store
36 | *.iml
--------------------------------------------------------------------------------
/sampleapp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | VERSION_NAME=0.2
2 | VERSION_TAG=v0.2
3 | GROUP=com.azimolabs.maskformatter
4 |
5 | POM_DESCRIPTION=Add text masking functionality to Android EditText
6 | POM_URL=https://github.com/AzimoLabs/MaskFormatter
7 | GIT_URL=https://github.com/AzimoLabs/MaskFormatter.git
8 | POM_SCM_URL=https://github.com/AzimoLabs/MaskFormatter
9 | POM_SCM_CONNECTION=scm:git@github.com/AzimoLabs/MaskFormatter.git
10 | POM_SCM_DEV_CONNECTION=scm:git@github.com:AzimoLabs/MaskFormatter.git
11 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
12 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
13 | POM_LICENCE_DIST=repo
14 | POM_DEVELOPER_ID=azimolabs
15 | POM_DEVELOPER_NAME=Azimo Labs
16 |
--------------------------------------------------------------------------------
/sampleapp/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/maciek/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/maskformatter/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/maciek/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/maskformatter/src/main/java/com/azimolabs/maskformatter/CharInputType.java:
--------------------------------------------------------------------------------
1 | package com.azimolabs.maskformatter;
2 |
3 | import android.text.InputType;
4 |
5 | /**
6 | * Created by maciek on 21.03.2016.
7 | */
8 | public class CharInputType {
9 |
10 | public static int getKeyboardTypeForNextChar(char nextChar) {
11 | if (Character.isDigit(nextChar)) {
12 | return InputType.TYPE_CLASS_NUMBER;
13 | }
14 |
15 | switch (nextChar) {
16 | case 'd':
17 | return InputType.TYPE_CLASS_NUMBER;
18 | case 'A':
19 | case 'Z':
20 | case '%':
21 | return InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS;
22 | }
23 |
24 | return InputType.TYPE_CLASS_TEXT;
25 | }
26 |
27 | }
--------------------------------------------------------------------------------
/sampleapp/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "com.azimolabs.maskformatter.sampleapp"
9 | minSdkVersion 7
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 |
25 | //Uncomment to use local version of library
26 | // compile project(path: ':maskformatter')
27 |
28 | compile 'com.azimolabs.maskformatter:maskformatter:0.1'
29 | }
30 |
--------------------------------------------------------------------------------
/maskformatter/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | minSdkVersion 7
9 | targetSdkVersion 23
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | compile fileTree(dir: 'libs', include: ['*.jar'])
23 |
24 | testCompile 'junit:junit:4.12'
25 | testCompile 'org.mockito:mockito-core:1.10.19'
26 | testCompile('org.robolectric:robolectric:3.0') {
27 | exclude module: 'classworlds'
28 | exclude module: 'commons-logging'
29 | exclude module: 'httpclient'
30 | exclude module: 'maven-artifact'
31 | exclude module: 'maven-artifact-manager'
32 | exclude module: 'maven-error-diagnostics'
33 | exclude module: 'maven-model'
34 | exclude module: 'maven-project'
35 | exclude module: 'maven-settings'
36 | exclude module: 'plexus-container-default'
37 | exclude module: 'plexus-interpolation'
38 | exclude module: 'plexus-utils'
39 | exclude module: 'wagon-file'
40 | exclude module: 'wagon-http-lightweight'
41 | exclude module: 'wagon-provider-api'
42 | }
43 | }
44 |
45 | apply from: rootProject.file('gradle/gradle-bintray-push.gradle')
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/azimolabs/maskformatter/sampleapp/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.azimolabs.maskformatter.sampleapp;
2 |
3 | import android.app.Activity;
4 | import android.os.Bundle;
5 | import android.widget.EditText;
6 |
7 | import com.azimolabs.maskformatter.MaskFormatter;
8 |
9 | public class MainActivity extends Activity {
10 |
11 | private static final String IBAN_MASK = "AA 9999 AAAA wwww wwww wwww";
12 |
13 | private static final String NUMBERS_MASK = "dd DD 1234 5678 90";
14 |
15 | private static final String CHARS_MASK = "AAZZ aazz @@ww ##%%";
16 |
17 | private static final String NUMBERS_MASKED_MASK = "999 99 9999";
18 |
19 | private static final String NUMBERS_DASHED_MASK = "999-999-9999";
20 |
21 | @Override
22 | protected void onCreate(Bundle savedInstanceState) {
23 | super.onCreate(savedInstanceState);
24 | setContentView(R.layout.activity_main);
25 |
26 | setupEditText(R.id.etIban, IBAN_MASK);
27 | setupEditText(R.id.etNumbers, NUMBERS_MASK);
28 | setupEditText(R.id.etChars, CHARS_MASK);
29 | setupEditText(R.id.ssnChars, NUMBERS_MASKED_MASK);
30 | setupEditTextWithDashes(R.id.etDashedNumbers, NUMBERS_DASHED_MASK);
31 | }
32 |
33 | private void setupEditText(int layoutId, String mask) {
34 | EditText field = (EditText) findViewById(layoutId);
35 | field.addTextChangedListener(new MaskFormatter(mask, field));
36 | }
37 |
38 | private void setupEditTextWithDashes(int layoutId, String mask) {
39 | EditText field = (EditText) findViewById(layoutId);
40 | field.addTextChangedListener(new MaskFormatter(mask, field, '-'));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/gradle/gradle-bintray-push.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.jfrog.bintray'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 |
4 | group = GROUP
5 | version = VERSION_NAME
6 |
7 | install {
8 | repositories.mavenInstaller {
9 | pom {
10 | project {
11 | packaging 'jar'
12 | groupId GROUP
13 | artifactId "maskformatter"
14 |
15 | name "MaskFormatter"
16 | description POM_DESCRIPTION
17 | url POM_URL
18 |
19 | licenses {
20 | license {
21 | name POM_LICENCE_NAME
22 | url POM_LICENCE_URL
23 | Distribution POM_LICENCE_DIST
24 | }
25 | }
26 |
27 | developers {
28 | developer {
29 | id POM_DEVELOPER_ID
30 | name POM_DEVELOPER_NAME
31 | }
32 | }
33 |
34 | scm {
35 | url POM_SCM_URL
36 | connection POM_SCM_CONNECTION
37 | developerConnection POM_SCM_DEV_CONNECTION
38 | }
39 | }
40 | }
41 | }
42 | }
43 |
44 | bintray {
45 | // Global gradle.properties
46 | user = project.hasProperty('BINTRAY_AZIMO_USER') ? project.getProperty('BINTRAY_AZIMO_USER') : ""
47 | key = project.hasProperty('BINTRAY_AZIMO_KEY') ? project.getProperty('BINTRAY_AZIMO_KEY') : ""
48 |
49 | configurations = ['archives']
50 | pkg {
51 | repo = 'maven'
52 | name = 'MaskFormatter'
53 | desc = POM_DESCRIPTION
54 | websiteUrl = POM_URL
55 | vcsUrl = GIT_URL
56 | licenses = ["Apache-2.0"]
57 | publish = true
58 | publicDownloadNumbers = true
59 | version {
60 | desc = POM_DESCRIPTION
61 | gpg {
62 | sign = true
63 | passphrase = project.hasProperty('BINTRAY_AZIMO_GPG_PASSWORD') ? project.getProperty('BINTRAY_AZIMO_GPG_PASSWORD') : ""
64 | }
65 | }
66 | }
67 | }
68 |
69 | task sourcesJar(type: Jar) {
70 | from android.sourceSets.main.java.srcDirs
71 | classifier = 'sources'
72 | }
73 |
74 | task javadoc(type: Javadoc) {
75 | source = android.sourceSets.main.java.srcDirs
76 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
77 | }
78 |
79 | task javadocJar(type: Jar, dependsOn: javadoc) {
80 | classifier = 'javadoc'
81 | from javadoc.destinationDir
82 | }
83 |
84 | artifacts {
85 | archives javadocJar
86 | archives sourcesJar
87 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/sampleapp/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
15 |
16 |
21 |
22 |
28 |
29 |
34 |
35 |
41 |
42 |
47 |
48 |
54 |
55 |
60 |
61 |
67 |
68 |
73 |
74 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MaskFormatter
2 | MaskFormatter adds mask functionality to your EditText. It will prevent user from inserting not allowed signs, and format input as well.
3 |
4 | 
5 |
6 | 
7 |
8 | Mask should be built from characters listed below (java regex associated to character given after colon):
9 |
10 | ```
11 | '9': '[0-9]',
12 | '8': '[0-8]',
13 | '7': '[0-7]',
14 | '6': '[0-6]',
15 | '5': '[0-5]',
16 | '4': '[0-4]',
17 | '3': '[0-3]',
18 | '2': '[0-2]',
19 | '1': '[0-1]',
20 | '0': '[0]',
21 |
22 | '*': '.',
23 | 'W': '\W',
24 | 'd': '\d',
25 | 'D': '\D',
26 | 's': '\s',
27 | 'S': '\S',
28 |
29 | 'A': '[A-Z]',
30 | 'a': '[a-z]',
31 | 'Z': '[A-ZÇÀÁÂÃÈÉÊẼÌÍÎĨÒÓÔÕÙÚÛŨ]',
32 | 'z': '[a-zçáàãâéèêẽíìĩîóòôõúùũüû]',
33 | '@': '[a-zA-Z]',
34 | '#': '[a-zA-ZçáàãâéèêẽíìĩîóòôõúùũüûÇÀÁÂÃÈÉÊẼÌÍÎĨÒÓÔÕÙÚÛŨ]',
35 |
36 | '%': '[A-Z0-9]',
37 | 'w': '[a-zA-Z0-9]'
38 | ```
39 |
40 | # Usage
41 | In your `build.gradle`:
42 |
43 | ```gradle
44 |
45 | dependencies {
46 | compile 'com.azimolabs.maskformatter:maskformatter:0.2'
47 | }
48 |
49 | ```
50 |
51 | Library is distributed via jCenter Maven repository. Make sure that you have it in your root gradle config:
52 |
53 | ```gradle
54 | allprojects {
55 | repositories {
56 | jcenter()
57 | }
58 | }
59 | ```
60 |
61 | Then you can use it like this:
62 |
63 | ```java
64 | public MainActivity extends Activity {
65 |
66 | private static final IBAN_MASK = "AA 99 9999 AAAA wwww wwww wwww";
67 |
68 | @Override
69 | public void onCreate(Bundle savedInstanceState) {
70 | super.onCreate(savedInstanceState);
71 | setContentView(R.layout.sample_layout);
72 |
73 | EditText ibanEditText = (EditText) findViewById(R.id.etIban);
74 | MaskFormatter ibanMaskFormatter = new MaskFormatter(IBAN_MASK, ibanEditText);
75 | ibanEditText.addTextChangedListener(ibanMaskFormatter);
76 | }
77 |
78 | }
79 | ```
80 |
81 | And make sure that you disabled suggestions from used EditText:
82 |
83 | ```xml
84 |
89 | ```
90 |
91 | # License
92 |
93 | ```
94 | Copyright (C) 2016 AzimoLabs
95 |
96 | Licensed under the Apache License, Version 2.0 (the "License");
97 | you may not use this file except in compliance with the License.
98 | You may obtain a copy of the License at
99 |
100 | http://www.apache.org/licenses/LICENSE-2.0
101 |
102 | Unless required by applicable law or agreed to in writing, software
103 | distributed under the License is distributed on an "AS IS" BASIS,
104 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
105 | See the License for the specific language governing permissions and
106 | limitations under the License.
107 | ```
108 |
109 |
110 | # Towards financial services available to all
111 | We’re working throughout the company to create faster, cheaper, and more available financial services all over the world, and here are some of the techniques that we’re utilizing. There’s still a long way ahead of us, and if you’d like to be part of that journey, check out our [careers page](https://bit.ly/3vajnu6).
112 |
--------------------------------------------------------------------------------
/maskformatter/src/main/java/com/azimolabs/maskformatter/CharTransforms.java:
--------------------------------------------------------------------------------
1 | package com.azimolabs.maskformatter;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.regex.Pattern;
6 |
7 | /**
8 | * Created by maciek on 16.03.2016.
9 | */
10 | public class CharTransforms {
11 |
12 | private static Map transformMap = new HashMap<>();
13 |
14 | private static class TransformPattern {
15 |
16 | private Pattern pattern;
17 | private boolean upperCase;
18 | private boolean lowerCase;
19 |
20 | public TransformPattern(String pattern, boolean upperCase, boolean lowerCase) {
21 | this.pattern = Pattern.compile(pattern);
22 | this.upperCase = upperCase;
23 | this.lowerCase = lowerCase;
24 | }
25 |
26 | public char transformChar(char stringChar) throws InvalidTextException {
27 | char modified;
28 | if (upperCase) {
29 | modified = Character.toUpperCase(stringChar);
30 | } else if (lowerCase) {
31 | modified = Character.toLowerCase(stringChar);
32 | } else {
33 | modified = stringChar;
34 | }
35 |
36 | if (!pattern.matcher(modified + "").matches()) {
37 | throw new InvalidTextException();
38 | }
39 | return modified;
40 | }
41 |
42 | }
43 |
44 | static {
45 | transformMap.put('9', new TransformPattern("[0-9]", false, false));
46 | transformMap.put('8', new TransformPattern("[0-8]", false, false));
47 | transformMap.put('7', new TransformPattern("[0-7]", false, false));
48 | transformMap.put('6', new TransformPattern("[0-6]", false, false));
49 | transformMap.put('5', new TransformPattern("[0-5]", false, false));
50 | transformMap.put('4', new TransformPattern("[0-4]", false, false));
51 | transformMap.put('3', new TransformPattern("[0-3]", false, false));
52 | transformMap.put('2', new TransformPattern("[0-2]", false, false));
53 | transformMap.put('1', new TransformPattern("[0-1]", false, false));
54 | transformMap.put('0', new TransformPattern("[0]", false, false));
55 |
56 | transformMap.put('*', new TransformPattern(".", false, false));
57 | transformMap.put('W', new TransformPattern("\\W", false, false));
58 | transformMap.put('d', new TransformPattern("\\d", false, false));
59 | transformMap.put('D', new TransformPattern("\\D", false, false));
60 | transformMap.put('s', new TransformPattern("\\s", false, false));
61 | transformMap.put('S', new TransformPattern("\\S", false, false));
62 |
63 | transformMap.put('A', new TransformPattern("[A-Z]", true, false));
64 | transformMap.put('a', new TransformPattern("[a-z]", false, true));
65 |
66 | transformMap.put('Z', new TransformPattern("[A-ZÇÀÁÂÃÈÉÊẼÌÍÎĨÒÓÔÕÙÚÛŨ]", true, false));
67 | transformMap.put('z', new TransformPattern("[a-zçáàãâéèêẽíìĩîóòôõúùũüû]", false, true));
68 |
69 | transformMap.put('@', new TransformPattern("[a-zA-Z]", false, false));
70 | transformMap.put('#', new TransformPattern("[A-Za-zçáàãâéèêẽíìĩîóòôõúùũüûÇÀÁÂÃÈÉÊẼÌÍÎĨÒÓÔÕÙÚÛŨ]", false, false));
71 |
72 | transformMap.put('%', new TransformPattern("[A-Z0-9]", true, false));
73 | transformMap.put('w', new TransformPattern("\\w", false, false));
74 | }
75 |
76 | public static char transformChar(char stringChar, char maskChar) throws InvalidTextException {
77 | TransformPattern transform = transformMap.get(maskChar);
78 | if (transform == null) {
79 | return stringChar;
80 | }
81 |
82 | return transform.transformChar(stringChar);
83 | }
84 |
85 | }
--------------------------------------------------------------------------------
/maskformatter/src/test/java/com/azimolabs/maskformatter/CharTransformsTests.java:
--------------------------------------------------------------------------------
1 | package com.azimolabs.maskformatter;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | import static org.junit.Assert.assertEquals;
7 |
8 | /**
9 | * Created by maciek on 16.03.2016.
10 | */
11 | public class CharTransformsTests {
12 |
13 | @Test
14 | public void testCharTransforms() throws InvalidTextException {
15 | char transformed = CharTransforms.transformChar('a', 'A');
16 | assertEquals(transformed, 'A');
17 |
18 | transformed = CharTransforms.transformChar('A', 'a');
19 | assertEquals(transformed, 'a');
20 |
21 | transformed = CharTransforms.transformChar('A', 'z');
22 | assertEquals(transformed, 'a');
23 |
24 | transformed = CharTransforms.transformChar('a', 'Z');
25 | assertEquals(transformed, 'A');
26 |
27 | transformed = CharTransforms.transformChar('a', '%');
28 | assertEquals(transformed, 'A');
29 |
30 | transformed = CharTransforms.transformChar('a', '@');
31 | assertEquals(transformed, 'a');
32 | }
33 |
34 | @Test
35 | public void testCharWordValidation() {
36 | try {
37 | CharTransforms.transformChar('à', 'A');
38 | Assert.fail();
39 | } catch (InvalidTextException ite) {
40 |
41 | }
42 |
43 | try {
44 | CharTransforms.transformChar('à', 'a');
45 | Assert.fail();
46 | } catch (InvalidTextException ite) {
47 |
48 | }
49 |
50 | try {
51 | CharTransforms.transformChar('!', 'w');
52 | Assert.fail();
53 | } catch (InvalidTextException ite) {
54 |
55 | }
56 |
57 | try {
58 | CharTransforms.transformChar('à', 'Z');
59 | CharTransforms.transformChar('à', 'z');
60 | CharTransforms.transformChar('_', 'w');
61 | CharTransforms.transformChar('2', 'w');
62 | CharTransforms.transformChar('c', 'w');
63 | CharTransforms.transformChar('!', 'W');
64 | } catch (InvalidTextException ite) {
65 | Assert.fail();
66 | }
67 |
68 | }
69 |
70 | @Test
71 | public void testWhitecharsValidation() {
72 | try {
73 | CharTransforms.transformChar('_', 's');
74 | Assert.fail();
75 | } catch (InvalidTextException ite) {
76 |
77 | }
78 |
79 | try {
80 | CharTransforms.transformChar('\t', 'S');
81 | Assert.fail();
82 | } catch (InvalidTextException ite) {
83 |
84 | }
85 |
86 | try {
87 | CharTransforms.transformChar('\t', 's');
88 | CharTransforms.transformChar('_', 'S');
89 | } catch (InvalidTextException ite) {
90 | Assert.fail();
91 | }
92 | }
93 |
94 | @Test
95 | public void testCharNumberValidation() {
96 | try {
97 | CharTransforms.transformChar('8', '7');
98 | Assert.fail();
99 | } catch (InvalidTextException ite) {
100 |
101 | }
102 |
103 | try {
104 | CharTransforms.transformChar('8', 'D');
105 | Assert.fail();
106 | } catch (InvalidTextException ite) {
107 |
108 | }
109 |
110 | try {
111 | CharTransforms.transformChar('8', '8');
112 | CharTransforms.transformChar('8', '9');
113 | CharTransforms.transformChar('8', 'd');
114 | CharTransforms.transformChar('ć', 'D');
115 | } catch (InvalidTextException ite) {
116 | Assert.fail();
117 | }
118 |
119 | }
120 |
121 | @Test
122 | public void testShouldReturnSameCharWhenMaskCharIsUnrecognized() throws InvalidTextException {
123 | char transformed = CharTransforms.transformChar('ź', '?');
124 | assertEquals(transformed, 'ź');
125 | }
126 |
127 | @Test
128 | public void testShouldAnyCharBePassedByStarMaskElement() throws InvalidTextException {
129 | CharTransforms.transformChar('!', '*');
130 | CharTransforms.transformChar('A', '*');
131 | CharTransforms.transformChar('ą', '*');
132 | CharTransforms.transformChar('_', '*');
133 | CharTransforms.transformChar('\t', '*');
134 | CharTransforms.transformChar(' ', '*');
135 | CharTransforms.transformChar('5', '*');
136 | CharTransforms.transformChar(';', '*');
137 | }
138 |
139 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/maskformatter/src/main/java/com/azimolabs/maskformatter/MaskFormatter.java:
--------------------------------------------------------------------------------
1 | package com.azimolabs.maskformatter;
2 |
3 | import android.os.Build;
4 | import android.text.Editable;
5 | import android.text.InputType;
6 | import android.text.TextWatcher;
7 | import android.widget.EditText;
8 |
9 | /**
10 | * Created by maciek on 16.03.2016.
11 | */
12 | public class MaskFormatter implements TextWatcher {
13 |
14 | private static final char SPACE = ' ';
15 |
16 | private final String mask;
17 | private final EditText maskedField;
18 | private final char maskCharacter;
19 |
20 | private boolean editTextChange;
21 | private int newIndex;
22 | private String textBefore;
23 | private int selectionBefore;
24 | private int passwordMask;
25 |
26 | public MaskFormatter(String mask, EditText maskedField) {
27 | this(mask, maskedField, SPACE);
28 | }
29 |
30 | public MaskFormatter(String mask, EditText maskedField, char maskCharacter) {
31 | this.mask = mask;
32 | this.maskedField = maskedField;
33 | this.maskCharacter = maskCharacter;
34 | this.passwordMask = getPasswordMask(maskedField);
35 | setInputTypeBasedOnMask();
36 | }
37 |
38 | private int getPasswordMask(EditText maskedField) {
39 | int inputType = maskedField.getInputType();
40 | int maskedFieldPasswordMask = (inputType & InputType.TYPE_TEXT_VARIATION_PASSWORD
41 | | inputType & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
42 |
43 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
44 | maskedFieldPasswordMask |= inputType & InputType.TYPE_NUMBER_VARIATION_PASSWORD;
45 | maskedFieldPasswordMask |= inputType & InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD;
46 | }
47 |
48 | return maskedFieldPasswordMask;
49 | }
50 |
51 | @Override
52 | public void beforeTextChanged(CharSequence s, int index, int toBeReplacedCount, int addedCount) {
53 | textBefore = s.toString();
54 | selectionBefore = maskedField.getSelectionEnd();
55 | }
56 |
57 | @Override
58 | public void onTextChanged(CharSequence s, int index, int replacedCount, int addedCount) {
59 | if (editTextChange) {
60 | maskedField.setSelection(newIndex);
61 | editTextChange = false;
62 | return;
63 | }
64 |
65 | try {
66 | String appliedMaskString = applyMask(s.toString());
67 | if (!appliedMaskString.equals(s.toString())) {
68 | editTextChange = true;
69 | newIndex = countNewIndex(addedCount, appliedMaskString);
70 | maskedField.setText(appliedMaskString);
71 | }
72 | } catch (InvalidTextException ie) {
73 | editTextChange = true;
74 | newIndex = selectionBefore;
75 | maskedField.setText(textBefore);
76 | }
77 | }
78 |
79 | private int countNewIndex(int addedCount, String appliedMaskString) {
80 | if (appliedMaskString.length() == 0) {
81 | return 0;
82 | }
83 |
84 | if (addedCount < 1) {
85 | return newIndexForRemovingCharacters(appliedMaskString);
86 | }
87 |
88 | return newIndexForAddingCharacters(appliedMaskString);
89 | }
90 |
91 | private int newIndexForRemovingCharacters(String appliedMaskString) {
92 | if (selectionBefore > appliedMaskString.length()) {
93 | selectionBefore = appliedMaskString.length();
94 | } else {
95 | selectionBefore = selectionBefore - 1;
96 | }
97 |
98 | if (selectionBefore < 0) {
99 | return 0;
100 | }
101 |
102 | if (selectionBefore - 1 >= 0
103 | && appliedMaskString.charAt(selectionBefore - 1) == maskCharacter) {
104 | return selectionBefore - 1;
105 | }
106 |
107 | return selectionBefore;
108 | }
109 |
110 | private int newIndexForAddingCharacters(String appliedMaskString) {
111 | if (selectionBefore >= appliedMaskString.length()) {
112 | return appliedMaskString.length();
113 | }
114 |
115 | if (appliedMaskString.charAt(selectionBefore) == maskCharacter) {
116 | return selectionBefore + 2;
117 | }
118 |
119 | return selectionBefore + 1;
120 | }
121 |
122 | @Override
123 | public void afterTextChanged(Editable s) {
124 | if (editTextChange) {
125 | maskedField.setSelection(newIndex);
126 | }
127 | setInputTypeBasedOnMask();
128 | }
129 |
130 | private String applyMask(String newValue) throws InvalidTextException {
131 | String newValueWithoutSpaces = newValue.replaceAll(String.valueOf(maskCharacter), "");
132 | StringBuilder sb = new StringBuilder();
133 | int index = 0;
134 | for (char c : newValueWithoutSpaces.toCharArray()) {
135 | if (index >= mask.length()) {
136 | throw new InvalidTextException();
137 | }
138 | while (mask.charAt(index) == maskCharacter) {
139 | sb.append(maskCharacter);
140 | index++;
141 | }
142 | sb.append(applyMaskToChar(c, index));
143 | index++;
144 | }
145 |
146 | return sb.toString();
147 | }
148 |
149 | private char applyMaskToChar(char c, int maskIndex) throws InvalidTextException {
150 | return CharTransforms.transformChar(c, mask.charAt(maskIndex));
151 | }
152 |
153 | private void setInputTypeBasedOnMask() {
154 | int selection = maskedField.getSelectionEnd();
155 | if (selection >= mask.length()) {
156 | return;
157 | }
158 |
159 | char maskChar = getFirstNotWhiteCharFromMask();
160 | if (maskChar == maskCharacter) {
161 | return;
162 | }
163 |
164 | maskedField.setInputType(passwordMask | CharInputType.getKeyboardTypeForNextChar(maskChar));
165 | }
166 |
167 | private char getFirstNotWhiteCharFromMask() {
168 | int maskIndex = maskedField.getSelectionEnd();
169 | while (maskIndex < mask.length() && mask.charAt(maskIndex) == maskCharacter) {
170 | maskIndex++;
171 | }
172 | return mask.charAt(maskIndex);
173 | }
174 |
175 | public String getRawTextValue() {
176 | return maskedField.getText().toString().replaceAll(String.valueOf(maskCharacter), "");
177 | }
178 |
179 | }
180 |
--------------------------------------------------------------------------------
/maskformatter/src/test/java/com/azimolabs/maskformatter/MaskFormatterTests.java:
--------------------------------------------------------------------------------
1 | package com.azimolabs.maskformatter;
2 |
3 | import android.text.InputType;
4 | import android.widget.EditText;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 | import org.mockito.Mock;
8 | import org.mockito.MockitoAnnotations;
9 |
10 | import static org.mockito.Matchers.anyInt;
11 | import static org.mockito.Mockito.never;
12 | import static org.mockito.Mockito.reset;
13 | import static org.mockito.Mockito.times;
14 | import static org.mockito.Mockito.verify;
15 | import static org.mockito.Mockito.when;
16 |
17 | /**
18 | * Created by maciek on 16.03.2016.
19 | */
20 | public class MaskFormatterTests {
21 |
22 | MaskFormatter filter;
23 |
24 | @Mock
25 | EditText mockEditText;
26 |
27 | @Before
28 | public void setUp() {
29 | MockitoAnnotations.initMocks(this);
30 |
31 | String mask = "99 AAAA wwww wwww wwww wwww";
32 | filter = new MaskFormatter(mask, mockEditText);
33 | }
34 |
35 | @Test
36 | public void testShouldFormatProperlyAddedCharToTextWithIBANMask() {
37 | when(mockEditText.getSelectionEnd()).thenReturn(2);
38 |
39 | filter.beforeTextChanged("34", 2, 0, 1);
40 | filter.onTextChanged("34s", 2, 0, 1);
41 |
42 | verify(mockEditText).setText("34 S");
43 |
44 | filter.onTextChanged("34 S", 2, 0, 1);
45 | verify(mockEditText).setSelection(4);
46 |
47 | // ----
48 |
49 | reset(mockEditText);
50 | when(mockEditText.getSelectionEnd()).thenReturn(3);
51 |
52 | filter.beforeTextChanged("34 S", 2, 0, 1);
53 | filter.onTextChanged("34 aS", 2, 0, 1);
54 |
55 | verify(mockEditText).setText("34 AS");
56 |
57 | filter.onTextChanged("34 AS", 2, 0, 1);
58 | verify(mockEditText).setSelection(4);
59 |
60 | // ----
61 |
62 | reset(mockEditText);
63 | when(mockEditText.getSelectionEnd()).thenReturn(4);
64 |
65 | filter.beforeTextChanged("34 AS", 2, 0, 1);
66 | filter.onTextChanged("34 A1S", 2, 0, 1);
67 |
68 | verify(mockEditText).setText("34 AS");
69 |
70 | filter.onTextChanged("34 AS", 2, 0, 1);
71 | verify(mockEditText).setSelection(4);
72 |
73 | // ----
74 |
75 | reset(mockEditText);
76 | when(mockEditText.getSelectionEnd()).thenReturn(27);
77 |
78 | filter.beforeTextChanged("34 ASFG asdf qwer 3412 rter", 2, 0, 1);
79 | filter.onTextChanged("34 ASFG asdf qwer 3412 rtera", 2, 0, 1);
80 |
81 | verify(mockEditText).setText("34 ASFG asdf qwer 3412 rter");
82 |
83 | filter.onTextChanged("34 ASFG asdf qwer 3412 rter", 2, 0, 1);
84 | verify(mockEditText).setSelection(27);
85 |
86 | // ----
87 |
88 | reset(mockEditText);
89 | when(mockEditText.getSelectionEnd()).thenReturn(9);
90 |
91 | filter.beforeTextChanged("34 ASFG asdf qwer 3412 rter", 2, 0, 1);
92 | filter.onTextChanged("34 ASFG assdf qwer 3412 rter", 2, 0, 1);
93 |
94 | verify(mockEditText).setText("34 ASFG asdf qwer 3412 rter");
95 |
96 | filter.onTextChanged("34 ASFG asdf qwer 3412 rter", 2, 0, 1);
97 | verify(mockEditText).setSelection(9);
98 |
99 | }
100 |
101 | @Test
102 | public void testShouldFormatProperlyPastedFragmentToTextWithIBANMask() {
103 | when(mockEditText.getSelectionEnd()).thenReturn(0);
104 |
105 | filter.beforeTextChanged("", 0, 0, 1);
106 | filter.onTextChanged("34ASFGasdfqwer3412rter", 0, 0, 22);
107 |
108 | verify(mockEditText).setText("34 ASFG asdf qwer 3412 rter");
109 |
110 | filter.onTextChanged("34 ASFG assdf qwer 3412 rter", 0, 0, 28);
111 |
112 | // ----
113 |
114 | filter.beforeTextChanged("34 ASF", 4, 0, 1);
115 | filter.onTextChanged("34 ASqwerF", 4, 0, 4);
116 |
117 | verify(mockEditText).setText("34 ASQW erF");
118 | }
119 |
120 | @Test
121 | public void testShouldFormatProperlyRemovedCharToTextWithIBANMask() {
122 | when(mockEditText.getSelectionEnd()).thenReturn(4);
123 |
124 | filter.beforeTextChanged("34 S", 3, 1, 0);
125 | filter.onTextChanged("34 ", 3, 1, 0);
126 |
127 | verify(mockEditText).setText("34");
128 |
129 | filter.onTextChanged("34", 2, 1, 0);
130 | verify(mockEditText).setSelection(2);
131 |
132 | // ----
133 |
134 | reset(mockEditText);
135 | when(mockEditText.getSelectionEnd()).thenReturn(3);
136 |
137 | filter.beforeTextChanged("34 SGHA a", 3, 1, 0);
138 | filter.onTextChanged("34 GHA a ", 3, 1, 0);
139 |
140 | verify(mockEditText).setText("34 GHAA");
141 |
142 | filter.onTextChanged("34 GHAA ", 7, 1, 0);
143 |
144 | verify(mockEditText).setSelection(2);
145 |
146 | // ---
147 |
148 | reset(mockEditText);
149 | when(mockEditText.getSelectionEnd()).thenReturn(2);
150 |
151 | filter.beforeTextChanged("35 S", 2, 1, 0);
152 | filter.onTextChanged("3 S", 2, 1, 0);
153 |
154 | verify(mockEditText).setText("35 S");
155 |
156 | filter.onTextChanged("35 S", 1, 0, 1);
157 |
158 | verify(mockEditText).setSelection(2);
159 | }
160 |
161 | @Test
162 | public void testShouldFormatProperlyCutFragmentToTextWithIBANMask() {
163 | when(mockEditText.getSelectionEnd()).thenReturn(7);
164 |
165 | filter.beforeTextChanged("34 SGAH refa r", 7, 3, 0);
166 | filter.onTextChanged("34 S refa r", 7, 3, 0);
167 |
168 | verify(mockEditText).setText("34 SREF ar");
169 | }
170 |
171 | @Test
172 | public void testShouldSetProperInputTypeToTextWithIBANMask() {
173 | reset(mockEditText);
174 | String fieldCurrentValue = "1";
175 | when(mockEditText.getSelectionEnd()).thenReturn(fieldCurrentValue.length());
176 |
177 | filter.afterTextChanged(null);
178 |
179 | verify(mockEditText).setInputType(InputType.TYPE_CLASS_NUMBER);
180 |
181 | // ---
182 |
183 | reset(mockEditText);
184 | fieldCurrentValue = "11";
185 | when(mockEditText.getSelectionEnd()).thenReturn(fieldCurrentValue.length());
186 |
187 | filter.afterTextChanged(null);
188 |
189 | verify(mockEditText).setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
190 |
191 | // ---
192 |
193 | reset(mockEditText);
194 | fieldCurrentValue = "11 ABCD cd";
195 | when(mockEditText.getSelectionEnd()).thenReturn(fieldCurrentValue.length());
196 |
197 | filter.afterTextChanged(null);
198 |
199 | verify(mockEditText).setInputType(InputType.TYPE_CLASS_TEXT);
200 |
201 | // ---
202 |
203 | fieldCurrentValue = "99 ABCD acbd 1234 efgh ijkl";
204 | reset(mockEditText);
205 | when(mockEditText.getSelectionEnd()).thenReturn(fieldCurrentValue.length());
206 |
207 | filter.afterTextChanged(null);
208 |
209 | verify(mockEditText, never()).setInputType(anyInt());
210 | }
211 |
212 | @Test
213 | public void testShouldSetProperInputTypeToPassword() {
214 | when(mockEditText.getInputType()).thenReturn(InputType.TYPE_TEXT_VARIATION_PASSWORD
215 | | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
216 |
217 | String mask = "99 AAAA wwww wwww wwww wwww";
218 | filter = new MaskFormatter(mask, mockEditText);
219 |
220 | String fieldCurrentValue = "99";
221 | when(mockEditText.getSelectionEnd()).thenReturn(fieldCurrentValue.length());
222 |
223 | filter.afterTextChanged(null);
224 |
225 | verify(mockEditText).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD
226 | | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
227 |
228 | // ---
229 |
230 | fieldCurrentValue = "99 ABCD";
231 | reset(mockEditText);
232 | when(mockEditText.getSelectionEnd()).thenReturn(fieldCurrentValue.length());
233 |
234 | filter.afterTextChanged(null);
235 |
236 | verify(mockEditText).setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
237 | | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
238 | }
239 |
240 | @Test
241 | public void testShouldSetProperInputTypeToNumberPassword() {
242 | when(mockEditText.getInputType()).thenReturn(InputType.TYPE_TEXT_VARIATION_PASSWORD);
243 |
244 | String mask = "999 99 9999";
245 | filter = new MaskFormatter(mask, mockEditText);
246 |
247 | String fieldCurrentValue = "123";
248 | when(mockEditText.getSelectionEnd()).thenReturn(fieldCurrentValue.length());
249 |
250 | filter.afterTextChanged(null);
251 |
252 | verify(mockEditText, times(2)).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD);
253 | }
254 |
255 | @Test
256 | public void testShouldSetProperInputTypeToTextWithDashesInMask() {
257 | String mask = "999-999-9999";
258 | filter = new MaskFormatter(mask, mockEditText, '-');
259 |
260 | reset(mockEditText);
261 | String fieldCurrentValue = "1";
262 | when(mockEditText.getSelectionEnd()).thenReturn(fieldCurrentValue.length());
263 |
264 | filter.afterTextChanged(null);
265 |
266 | verify(mockEditText).setInputType(InputType.TYPE_CLASS_NUMBER);
267 |
268 | // ---
269 |
270 | reset(mockEditText);
271 | fieldCurrentValue = "111-11-1111";
272 | when(mockEditText.getSelectionEnd()).thenReturn(fieldCurrentValue.length());
273 |
274 | filter.afterTextChanged(null);
275 |
276 | verify(mockEditText).setInputType(InputType.TYPE_CLASS_NUMBER);
277 | }
278 | }
279 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------