Search code examples
androidandroid-edittext

Set error if the user tries to type after limit is reached in Android edittext


I tried via TextWatcher's afterTextChanged. All I want is display a toast message or set error on EditText if the user tries to insert characters after the limit is reached. I think it is possible. But don't know how to achieve this.

Update

My EditText coding is

<EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:maxLength="10"
        android:layout_marginTop="150dp"
        android:inputType="numberDecimal" >

Here if the user tries to enter more than 10 digit I want to display a toast or want to set error.

Update

 editText1.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (editText1.getText().length() >= 10)
                Toast.makeText(getApplicationContext(), "hi",
                        Toast.LENGTH_SHORT).show();
            return false;
        }
    });

Solution

  • You could get the maxLength of your editText with this. Then implement a keyListener.

     int maxLength = //getMaxLenght here;
        editText.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(editText.getText().toString().length()>= maxLength) {
                    //Show toast here
                }
                return false;
            }
        });