Remove dash from string on back or delete key?











up vote
1
down vote

favorite












I have code that adds a dash after 5th and 12th digit but on deleting these digits, the dash is not getting deleted after pressing the backspace key.
It gets stuck after deleting the last digit.



this is the code which I implemented from one of stack link.



EditText Cnic;
int maxLength = 15;
int len =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Cnic = (EditText)findViewById(R.id.cnic_edtext);

Cnic.setFilters(new InputFilter {new InputFilter.LengthFilter(maxLength)});
Cnic.addTextChangedListener(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) {
String str = s.toString();
if(s.length() == 5 || s.length() == 13){

str += "-";
Cnic.setText(str);
Cnic.setSelection(str.length());
}
}

@Override
public void afterTextChanged(Editable s) {

String str = s.toString();
len = str.length();
}
});

}









share|improve this question
























  • Have you viewed my answer? Did it work?
    – Ishaan
    Nov 10 at 20:32










  • no it does not works
    – Arsalan
    Nov 12 at 7:39















up vote
1
down vote

favorite












I have code that adds a dash after 5th and 12th digit but on deleting these digits, the dash is not getting deleted after pressing the backspace key.
It gets stuck after deleting the last digit.



this is the code which I implemented from one of stack link.



EditText Cnic;
int maxLength = 15;
int len =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Cnic = (EditText)findViewById(R.id.cnic_edtext);

Cnic.setFilters(new InputFilter {new InputFilter.LengthFilter(maxLength)});
Cnic.addTextChangedListener(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) {
String str = s.toString();
if(s.length() == 5 || s.length() == 13){

str += "-";
Cnic.setText(str);
Cnic.setSelection(str.length());
}
}

@Override
public void afterTextChanged(Editable s) {

String str = s.toString();
len = str.length();
}
});

}









share|improve this question
























  • Have you viewed my answer? Did it work?
    – Ishaan
    Nov 10 at 20:32










  • no it does not works
    – Arsalan
    Nov 12 at 7:39













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have code that adds a dash after 5th and 12th digit but on deleting these digits, the dash is not getting deleted after pressing the backspace key.
It gets stuck after deleting the last digit.



this is the code which I implemented from one of stack link.



EditText Cnic;
int maxLength = 15;
int len =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Cnic = (EditText)findViewById(R.id.cnic_edtext);

Cnic.setFilters(new InputFilter {new InputFilter.LengthFilter(maxLength)});
Cnic.addTextChangedListener(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) {
String str = s.toString();
if(s.length() == 5 || s.length() == 13){

str += "-";
Cnic.setText(str);
Cnic.setSelection(str.length());
}
}

@Override
public void afterTextChanged(Editable s) {

String str = s.toString();
len = str.length();
}
});

}









share|improve this question















I have code that adds a dash after 5th and 12th digit but on deleting these digits, the dash is not getting deleted after pressing the backspace key.
It gets stuck after deleting the last digit.



this is the code which I implemented from one of stack link.



EditText Cnic;
int maxLength = 15;
int len =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Cnic = (EditText)findViewById(R.id.cnic_edtext);

Cnic.setFilters(new InputFilter {new InputFilter.LengthFilter(maxLength)});
Cnic.addTextChangedListener(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) {
String str = s.toString();
if(s.length() == 5 || s.length() == 13){

str += "-";
Cnic.setText(str);
Cnic.setSelection(str.length());
}
}

@Override
public void afterTextChanged(Editable s) {

String str = s.toString();
len = str.length();
}
});

}






java android






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 17:12









Shashanth

2,49042136




2,49042136










asked Nov 10 at 9:31









Arsalan

259




259












  • Have you viewed my answer? Did it work?
    – Ishaan
    Nov 10 at 20:32










  • no it does not works
    – Arsalan
    Nov 12 at 7:39


















  • Have you viewed my answer? Did it work?
    – Ishaan
    Nov 10 at 20:32










  • no it does not works
    – Arsalan
    Nov 12 at 7:39
















Have you viewed my answer? Did it work?
– Ishaan
Nov 10 at 20:32




Have you viewed my answer? Did it work?
– Ishaan
Nov 10 at 20:32












no it does not works
– Arsalan
Nov 12 at 7:39




no it does not works
– Arsalan
Nov 12 at 7:39












2 Answers
2






active

oldest

votes

















up vote
0
down vote













I remember trying to do something similar to this a while ago. What you would have to do first is check that the change made to the text was a deletion. You also have to set the EditText's text to a substring of what was originally in there, this way the '-' is not part of it. I've made changes to your code below.



Check my code below and if you have any further questions, just comment below.



int length = 0;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
length = Cnic.getText().toString().length();
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int new_length = Cnic.getText().toString().length();
//The length has decreased, meaning that something was deleted.
if(length > new_length){
String str = s.toString();
if(s.length() == 5 || s.length() == 13){
//This sets the text to what was in the EditText, except it excludes the '-'
Cnic.setText(str.subString(0, s.length()-2));
Cnic.setSelection(str.length());
}
}else{
//The action that happened was not a delete, so just add the dashes to the text.
String str = s.toString();
if(s.length() == 5 || s.length() == 13){

str += "-";
Cnic.setText(str);
Cnic.setSelection(str.length());
}
}

}

@Override
public void afterTextChanged(Editable s) {

String str = s.toString();
len = str.length();
}


If this doesn't work, try putting the code from onTextChanged into afterTextChanged and see if that works. I think this answer should work.






share|improve this answer






























    up vote
    0
    down vote



    accepted










    I solved it using a library import tw.henrychuang.lib.AutoAddTextWatcher;



     EditText Cnic;
    int maxLength = 15;
    String str;
    Button save;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Cnic = (EditText)findViewById(R.id.cnic_edtext);
    save = (Button)findViewById(R.id.save_btn);
    Cnic.setFilters(new InputFilter {new InputFilter.LengthFilter(maxLength)});
    Cnic.setKeyListener(new DigitsKeyListener().getInstance("0123456789-"));


    Cnic.addTextChangedListener(new AutoAddTextWatcher(Cnic,
    "-",
    5, 12));


    save.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    str = Cnic.getText().toString();

    Toast.makeText(MainActivity.this, "Cnic "+str, Toast.LENGTH_SHORT).show();

    }
    });



    }





    share|improve this answer





















    • this works great
      – Arsalan
      Nov 12 at 9:10











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237636%2fremove-dash-from-string-on-back-or-delete-key%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    I remember trying to do something similar to this a while ago. What you would have to do first is check that the change made to the text was a deletion. You also have to set the EditText's text to a substring of what was originally in there, this way the '-' is not part of it. I've made changes to your code below.



    Check my code below and if you have any further questions, just comment below.



    int length = 0;
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    length = Cnic.getText().toString().length();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    int new_length = Cnic.getText().toString().length();
    //The length has decreased, meaning that something was deleted.
    if(length > new_length){
    String str = s.toString();
    if(s.length() == 5 || s.length() == 13){
    //This sets the text to what was in the EditText, except it excludes the '-'
    Cnic.setText(str.subString(0, s.length()-2));
    Cnic.setSelection(str.length());
    }
    }else{
    //The action that happened was not a delete, so just add the dashes to the text.
    String str = s.toString();
    if(s.length() == 5 || s.length() == 13){

    str += "-";
    Cnic.setText(str);
    Cnic.setSelection(str.length());
    }
    }

    }

    @Override
    public void afterTextChanged(Editable s) {

    String str = s.toString();
    len = str.length();
    }


    If this doesn't work, try putting the code from onTextChanged into afterTextChanged and see if that works. I think this answer should work.






    share|improve this answer



























      up vote
      0
      down vote













      I remember trying to do something similar to this a while ago. What you would have to do first is check that the change made to the text was a deletion. You also have to set the EditText's text to a substring of what was originally in there, this way the '-' is not part of it. I've made changes to your code below.



      Check my code below and if you have any further questions, just comment below.



      int length = 0;
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
      length = Cnic.getText().toString().length();
      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      int new_length = Cnic.getText().toString().length();
      //The length has decreased, meaning that something was deleted.
      if(length > new_length){
      String str = s.toString();
      if(s.length() == 5 || s.length() == 13){
      //This sets the text to what was in the EditText, except it excludes the '-'
      Cnic.setText(str.subString(0, s.length()-2));
      Cnic.setSelection(str.length());
      }
      }else{
      //The action that happened was not a delete, so just add the dashes to the text.
      String str = s.toString();
      if(s.length() == 5 || s.length() == 13){

      str += "-";
      Cnic.setText(str);
      Cnic.setSelection(str.length());
      }
      }

      }

      @Override
      public void afterTextChanged(Editable s) {

      String str = s.toString();
      len = str.length();
      }


      If this doesn't work, try putting the code from onTextChanged into afterTextChanged and see if that works. I think this answer should work.






      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        I remember trying to do something similar to this a while ago. What you would have to do first is check that the change made to the text was a deletion. You also have to set the EditText's text to a substring of what was originally in there, this way the '-' is not part of it. I've made changes to your code below.



        Check my code below and if you have any further questions, just comment below.



        int length = 0;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        length = Cnic.getText().toString().length();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        int new_length = Cnic.getText().toString().length();
        //The length has decreased, meaning that something was deleted.
        if(length > new_length){
        String str = s.toString();
        if(s.length() == 5 || s.length() == 13){
        //This sets the text to what was in the EditText, except it excludes the '-'
        Cnic.setText(str.subString(0, s.length()-2));
        Cnic.setSelection(str.length());
        }
        }else{
        //The action that happened was not a delete, so just add the dashes to the text.
        String str = s.toString();
        if(s.length() == 5 || s.length() == 13){

        str += "-";
        Cnic.setText(str);
        Cnic.setSelection(str.length());
        }
        }

        }

        @Override
        public void afterTextChanged(Editable s) {

        String str = s.toString();
        len = str.length();
        }


        If this doesn't work, try putting the code from onTextChanged into afterTextChanged and see if that works. I think this answer should work.






        share|improve this answer














        I remember trying to do something similar to this a while ago. What you would have to do first is check that the change made to the text was a deletion. You also have to set the EditText's text to a substring of what was originally in there, this way the '-' is not part of it. I've made changes to your code below.



        Check my code below and if you have any further questions, just comment below.



        int length = 0;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        length = Cnic.getText().toString().length();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        int new_length = Cnic.getText().toString().length();
        //The length has decreased, meaning that something was deleted.
        if(length > new_length){
        String str = s.toString();
        if(s.length() == 5 || s.length() == 13){
        //This sets the text to what was in the EditText, except it excludes the '-'
        Cnic.setText(str.subString(0, s.length()-2));
        Cnic.setSelection(str.length());
        }
        }else{
        //The action that happened was not a delete, so just add the dashes to the text.
        String str = s.toString();
        if(s.length() == 5 || s.length() == 13){

        str += "-";
        Cnic.setText(str);
        Cnic.setSelection(str.length());
        }
        }

        }

        @Override
        public void afterTextChanged(Editable s) {

        String str = s.toString();
        len = str.length();
        }


        If this doesn't work, try putting the code from onTextChanged into afterTextChanged and see if that works. I think this answer should work.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 10 at 13:39

























        answered Nov 10 at 13:33









        Ishaan

        7831417




        7831417
























            up vote
            0
            down vote



            accepted










            I solved it using a library import tw.henrychuang.lib.AutoAddTextWatcher;



             EditText Cnic;
            int maxLength = 15;
            String str;
            Button save;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Cnic = (EditText)findViewById(R.id.cnic_edtext);
            save = (Button)findViewById(R.id.save_btn);
            Cnic.setFilters(new InputFilter {new InputFilter.LengthFilter(maxLength)});
            Cnic.setKeyListener(new DigitsKeyListener().getInstance("0123456789-"));


            Cnic.addTextChangedListener(new AutoAddTextWatcher(Cnic,
            "-",
            5, 12));


            save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            str = Cnic.getText().toString();

            Toast.makeText(MainActivity.this, "Cnic "+str, Toast.LENGTH_SHORT).show();

            }
            });



            }





            share|improve this answer





















            • this works great
              – Arsalan
              Nov 12 at 9:10















            up vote
            0
            down vote



            accepted










            I solved it using a library import tw.henrychuang.lib.AutoAddTextWatcher;



             EditText Cnic;
            int maxLength = 15;
            String str;
            Button save;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Cnic = (EditText)findViewById(R.id.cnic_edtext);
            save = (Button)findViewById(R.id.save_btn);
            Cnic.setFilters(new InputFilter {new InputFilter.LengthFilter(maxLength)});
            Cnic.setKeyListener(new DigitsKeyListener().getInstance("0123456789-"));


            Cnic.addTextChangedListener(new AutoAddTextWatcher(Cnic,
            "-",
            5, 12));


            save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            str = Cnic.getText().toString();

            Toast.makeText(MainActivity.this, "Cnic "+str, Toast.LENGTH_SHORT).show();

            }
            });



            }





            share|improve this answer





















            • this works great
              – Arsalan
              Nov 12 at 9:10













            up vote
            0
            down vote



            accepted







            up vote
            0
            down vote



            accepted






            I solved it using a library import tw.henrychuang.lib.AutoAddTextWatcher;



             EditText Cnic;
            int maxLength = 15;
            String str;
            Button save;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Cnic = (EditText)findViewById(R.id.cnic_edtext);
            save = (Button)findViewById(R.id.save_btn);
            Cnic.setFilters(new InputFilter {new InputFilter.LengthFilter(maxLength)});
            Cnic.setKeyListener(new DigitsKeyListener().getInstance("0123456789-"));


            Cnic.addTextChangedListener(new AutoAddTextWatcher(Cnic,
            "-",
            5, 12));


            save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            str = Cnic.getText().toString();

            Toast.makeText(MainActivity.this, "Cnic "+str, Toast.LENGTH_SHORT).show();

            }
            });



            }





            share|improve this answer












            I solved it using a library import tw.henrychuang.lib.AutoAddTextWatcher;



             EditText Cnic;
            int maxLength = 15;
            String str;
            Button save;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Cnic = (EditText)findViewById(R.id.cnic_edtext);
            save = (Button)findViewById(R.id.save_btn);
            Cnic.setFilters(new InputFilter {new InputFilter.LengthFilter(maxLength)});
            Cnic.setKeyListener(new DigitsKeyListener().getInstance("0123456789-"));


            Cnic.addTextChangedListener(new AutoAddTextWatcher(Cnic,
            "-",
            5, 12));


            save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            str = Cnic.getText().toString();

            Toast.makeText(MainActivity.this, "Cnic "+str, Toast.LENGTH_SHORT).show();

            }
            });



            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 12 at 9:09









            Arsalan

            259




            259












            • this works great
              – Arsalan
              Nov 12 at 9:10


















            • this works great
              – Arsalan
              Nov 12 at 9:10
















            this works great
            – Arsalan
            Nov 12 at 9:10




            this works great
            – Arsalan
            Nov 12 at 9:10


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237636%2fremove-dash-from-string-on-back-or-delete-key%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()