Skip to main content

Android :Edittext Format space after Each 4 digit/Character


Replace EditText with your EditText Variable
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
EditText.addTextChangedListener(new TextWatcher() {

   
                    byte count1 = 0;
                    byte count2 = 0;
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        count1 = (byte)s.length();


                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        count2 = (byte)s.length();
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                   

                            String initial = EditText.getText().toString(); 

                            String formatted = "";
                            String preFormat = initial.replaceAll("-", "");

                            if (preFormat.length() % 4 == 0 && (count2 - count1 > 0)) {

                                for (int i = 0; i < preFormat.length(); i++) {
                                    formatted += preFormat.charAt(i);
                                if (((i + 1) % 4) == 0)
                                        formatted += "-";


                                }
                               EditText.removeTextChangedListener(this);
                                EditText.setText(formatted);
                                EditText.setSelection(formatted.length());
                                EditText.addTextChangedListener(this);


                            }
                        
                    }
                });

Comments

Post a Comment

share your thoughts ....