Is it possible to forbid the first number in a EditText to be “0”

谁说我不能喝 提交于 2020-07-18 12:47:15

问题


Hi I just want to know if it is possible to forbid the first number that the user can enter to be "0".

<EditText
        android:id="@+id/editText1"
        android:layout_width="50dp"
        android:layout_height="35dp"  
        android:layout_marginBottom="2dp" 
        android:maxLength="2"
        android:inputType="number"
        android:digits="123456789">
        <requestFocus />
    </EditText>

Using this code however prevents the user from entering "0" at all but I want just the first digit not to be "0"


回答1:


if you want to avoid the user from entering 0 only at the beginning, then try this:

editText1.addTextChangedListener(new TextWatcher(){
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            if (editText1.getText().toString().matches("^0") )
            {
                // Not allowed
                Toast.makeText(context, "not allowed", Toast.LENGTH_LONG).show();
                editText1.setText("");
            }
        }
        @Override
        public void afterTextChanged(Editable arg0) { }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    }); 



回答2:


For this purpose in Java, you could extend InputFilter class and set a minimum value of 10 for your EditText:

package your.package.name

import android.text.InputFilter;
import android.text.Spanned;

public class InputFilterMin implements InputFilter {

    private int min;

    public InputFilterMin(int min) {
        this.min = min;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {   
        try {
            int input = Integer.parseInt(dest.toString() + source.toString());
            if (input >= min)
                return null;
        } catch (NumberFormatException nfe) { }     
        return "";
    }
}

Then use this class in your activity:

EditText et = (EditText) findViewById(R.id.editText1);
et.setFilters(new InputFilter[]{ new InputFilterMin(10)});

now users are allowed to enter values equal or greater than 10.




回答3:


You can try this...

editText.addTextChangedListener(new TextWatcher() {

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

          long data=Long.parseLong(editText.toString());
          editText.setText(""+data);
        }

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

        }

        @Override
        public void afterTextChanged(Editable arg0) {

        }
    });


来源:https://stackoverflow.com/questions/24406447/is-it-possible-to-forbid-the-first-number-in-a-edittext-to-be-0

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