Last active
February 16, 2023 22:06
-
-
Save zhdanovartur/0ad0ae276accbedbf233 to your computer and use it in GitHub Desktop.
Android EditText credit card formatting (mask)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<EditText | |
android:id="@+id/creditCard" | |
android:inputType="number" | |
android:digits=" 1234567890" | |
android:maxLength="22" | |
/> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import android.support.v7.app.ActionBarActivity; | |
import android.os.Bundle; | |
public class SomeActivity extends ActionBarActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_some); | |
EditText creditCard = (EditText) findViewById(R.id.creditCard); | |
creditCard.addTextChangedListener(new CreditCardNumberFormattingTextWatcher()); | |
} | |
/** | |
* Formatting a credit card number: #### #### #### ####### | |
*/ | |
public static class CreditCardNumberFormattingTextWatcher implements TextWatcher { | |
private boolean lock; | |
@Override | |
public void onTextChanged(CharSequence s, int start, int before, int count) { | |
} | |
@Override | |
public void beforeTextChanged(CharSequence s, int start, int count, int after) { | |
} | |
@Override | |
public void afterTextChanged(Editable s) { | |
if (lock || s.length() > 16) { | |
return; | |
} | |
lock = true; | |
for (int i = 4; i < s.length(); i += 5) { | |
if (s.toString().charAt(i) != ' ') { | |
s.insert(i, " "); | |
} | |
} | |
lock = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment