4

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;
        }
    });
halfer
  • 19,824
  • 17
  • 99
  • 186
Gunaseelan
  • 14,415
  • 11
  • 80
  • 128

5 Answers5

1

On key listener doesn't work on Soft Input Keyboard.. From the Android reference at:

http://developer.android.com/reference/android/view/View.OnKeyListener.html

View.OnKeyListener

Class Overview Interface definition for a callback to be invoked when a hardware key event is dispatched to this view. The callback will be invoked before the key event is given to the view. This is only useful for hardware keyboards; a software input method has no obligation to trigger this listener.

So that means that TextWatcher is only your friend with editboxes and keyboard Inputs..

aimiliano
  • 1,105
  • 2
  • 12
  • 18
0

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;
        }
    });
Community
  • 1
  • 1
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • This should work. Try to print `maxLength` attribute and `editText.getText().toString().length()` before the if statement and tell me what it prints when you reach the limit. – Alexis C. Jun 10 '13 at 17:24
  • without if condition also nothing happened. – Gunaseelan Jun 10 '13 at 17:29
  • Is something printed when you type on your EditText ? – Alexis C. Jun 10 '13 at 17:30
  • No friend.. Nothing printed – Gunaseelan Jun 10 '13 at 17:54
  • I saw that you have set the listener on editText2 instead of editText1 maybe your filling the wrong editText. Could you try to print something just before the if statement please ? – Alexis C. Jun 10 '13 at 18:01
  • I got it friend. Thank you so much. Before I use both `addTextChangedListener` and `setOnKeyListener` separately. That is the problem. Now I was wrote `setOnKeyListener` to inside the `addTextChangedListener`. Now it is working fine. – Gunaseelan Jun 11 '13 at 02:01
0

Assuming you know the maximum length of the EditText you could use EditText.setError(String errorMsg) like this:

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (charSequence.toString().length() >= maxLength) {
            // show toast / error here
            String limitReached = "Maximum limit of characters reached!";
            editText.setError(limitReached);
        } else {
            // clear error
            editText.setError(null);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

It will look something like this. When that EditText is not in focus, the error message is not shown, but the error icon stays visible. You may use EditText.getError() to check if there is an error currently set on the EditText.

example of EditText.setError() appearance

This may be more than you are asking, but if you have an EditText with a dynamic character limit, I'd recommend hanging onto that value somewhere in the maxLength variable. (For example, the security code for a payment card varies based on card type)

However, you can do the following to programmatically check what the XML value of android:maxLength is currently set to:

    private int getEditTextCharacterLimit(EditText editText) {
        int defaultMaxLength = 5; // default value

        InputFilter[] filters = editText.getFilters();
        if (filters != null && filters[0] != null && filters[0] instanceof InputFilter.LengthFilter) {
            return ((InputFilter.LengthFilter) filters[0]).getMax();
        } else {
            return defaultMaxLength;
        }
    }

Here's how you would dynamically change the EditText's character limit programmatically.

Sampson
  • 662
  • 6
  • 17
0

This may be more than you are asking, but if you have an EditText with a dynamic character limit, I'd recommend hanging onto that value somewhere in the maxLength variable. (For example, the security code for a payment card varies based on card type)

nessrine
  • 1
  • 1
0
 val maxLength = 20
        edtPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable) {
                if (s.length > maxLength) {
                    s.delete(maxLength, s.length)
                    errorPassword.value = getLocalizationString(
                        R.string.passwordMaxLengthErrorMessage,
                        viewModel.maxPasswordLength
                    )
                }
            }
        })

I was dealing with the same issue and this is worked fine in my code (Kotlin)