Android: the first digit in the edit text cannot be zero

I have an EditText element with a number input type. I do not want users to be able to enter 0 as the first digit. Can I apply this using XML?

Here is what I have:

<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"/> 
+4
source share
4 answers

There is an alternative way to use textWatcher. Check the length of the edited text inside the afterTextChange.if length method is 1, and the line is 0, than deleting 0.

+4
source

No. But what you can do is check your activity every time the text changes, and then do everything you need to do when the first character is "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) { } }); 
+4
source
 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; } } 
0
source

Try it,

In XML,

 android:text="0" 

In java

 edit.setSelection(1); 
-1
source

Source: https://habr.com/ru/post/1489907/


All Articles