android: the first digit in the edit text can not

2019-04-07 16:24发布

I have an EditText element with a number input type. I don't want users to be able to enter 0 as the first digit. Can I enforce this using XML?

Here is what I have currently:

<EditText 
                android:id="@+id/main_edt_loan"
                android:layout_width="fill_parent"
                android:layout_height="40dip"
                android:background="@drawable/sample_editbox"
                android:ems="10"
                android:layout_margin="10dip"
                android:inputType="number"
                android:hint=""
                android:ellipsize="start" 
                android:maxLines="1"
                android:imeOptions="actionNext"
                android:textSize="18dip"
                android:gravity="center"
                android:digits="0123456789"
                android:maxLength="10"
                android:textColor="#000000"/>

5条回答
太酷不给撩
2楼-- · 2019-04-07 16:58

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();
            }
        }
    });
查看更多
地球回转人心会变
3楼-- · 2019-04-07 17:00
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;
    }
}
查看更多
狗以群分
4楼-- · 2019-04-07 17:18

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 .

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-04-07 17:22

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

}
}); 
查看更多
虎瘦雄心在
6楼-- · 2019-04-07 17:24

Try this,

In XML,

android:text="0"

In Java

edit.setSelection(1);
查看更多
登录 后发表回答