Search code examples
javaandroidandroid-edittext

how to delete the first character if the first character is a zero | Android | TextWatcher


i have question about how to delete the first character if the first character is a zero .

ex : 0887 to 887

here i'm using Text Watcher for my Edit Text. but it's not working

here is my code :

  @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (edtPhone.getText().charAt(start) == '0'){
            edtPhone.getText().delete(start, start);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

i'm so confused whats wrong in my code any help or suggestion will be appreciate


Solution

  • You can check if the first character is 0, then using the substring method extract the string except for the first character, then set it to the EditText.

    Code in Kotlin:

     phone_number_edt.doOnTextChanged { text: CharSequence?, start, count, after ->
            val length = text.toString().length
    
            if ((text.toString()[0] == '0')) {
                if (length > 1) {
                    email_edt.setText(
                        text.toString().substring(
                            1,
                            length
                        )
                    )
                }
            }
        }