In this example I will explain how you can build a TextInputLayout that shows credit card numeber.
The goal is to add a margin between every four digits without adding a space (" ") while you are inserting text.
You need to put a TextWatcher on a EditText.
The TextWatcher needs to add a margin every four digits.
Example:
private EditText etCreditCard;
private TextWatcher tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etCreditCard = (EditText) findViewById(R.id.cc);
tv = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
int textLength = etCreditCard.length();
if (textLength > 4) {
etCreditCard.removeTextChangedListener(tv);
if (textLength > 16) {
s.replace(16, textLength, "");
textLength = s.length();
}
for (int i = 1; i <= textLength; i++){
if( ((i % 4) == 0) && i > 1 && i < textLength ){
MarginSpan marginSPan = new MarginSpan(20);
s.setSpan(marginSPan, i - 1, i, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}else{
MarginSpan marginSPan = new MarginSpan(0);
s.setSpan(marginSPan, i - 1, i, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
etCreditCard.addTextChangedListener(tv);
}
}
};
etCreditCard.addTextChangedListener(tv);
}
Also if you click in the middle of the number and start to write there margins gets crazy