android: the first digit in the edit text can not be zero

不羁岁月 提交于 2019-12-04 04:47:42

There is an alternative way in which you can use textWatcher .Check length of editable text inside afterTextChange method .if length is 1 and string is 0 than remove 0 .

No. But what you can do is check in your activity every time the text changes and then do whatever needs to be done when the first symbol is a "0".

EditText main_edt_loan = (EditText) findViewById(R.id.main_edt_loan);
main_edt_loan.addTextChangedListener(new TextWatcher()
{
    public void afterTextChanged(Editable s) 
    {
        String x = s.toString
        if(x.startsWith("0"))
        {
            //your stuff here
        }
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
{

}
public void onTextChanged(CharSequence s, int start, int before, int count)
{

}
}); 

Its just simple as that.

edContactNumber.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) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == 1 && s.toString().startsWith("0")) {
                s.clear();
            }
        }
    });
Anish Vahora
public class PreventZeroAtBeginningFilter implements InputFilter {

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (dest.toString().equalsIgnoreCase("")) {
            String charSet = "0";
            if (source != null && charSet.contains(("" + source))) {
                return "";
            }
        }
        return null;
    }
}

Try this,

In XML,

android:text="0"

In Java

edit.setSelection(1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!