Skip to content

Instantly share code, notes, and snippets.

@zhdanovartur
Last active February 16, 2023 22:06
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zhdanovartur/0ad0ae276accbedbf233 to your computer and use it in GitHub Desktop.
Save zhdanovartur/0ad0ae276accbedbf233 to your computer and use it in GitHub Desktop.
Android EditText credit card formatting (mask)
<EditText
android:id="@+id/creditCard"
android:inputType="number"
android:digits=" 1234567890"
android:maxLength="22"
/>
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