Ad

Handle EditText Key Change Event With Input Type TEXT

My Use case is to restrict user after he has entered 4 lines in text box. Setting maxLines will not work to stop user.

I am surprise that Android is not providing key down/up event when input type is InputType.TYPE_CLASS_TEXT. I am receiving event for all other types. Below is my code.

        EditText et = new EditText(this);
        et.setMaxLines(3);
        et.setSingleLine(false);
        et.setInputType(InputType.TYPE_CLASS_TEXT);
        et.setHint("First edit text");
        et.setKeyListener(this); // This key listener is also not working.
        et.setOnKeyListener(new View.OnKeyListener() { 
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.d("MainActivity.class", "event received"); // This event is never called.
                return false;
            }
        });

@Override
public int getInputType() {
    return InputType.TYPE_CLASS_NUMBER;
}


@Override
public boolean onKeyDown(View view, Editable text, int keyCode, KeyEvent event) { // THIS EVENT HITS ONLY WHEN INPUT TYPE IS OTHER THAN TEXT.
    return false;
}

@Override
public boolean onKeyUp(View view, Editable text, int keyCode, KeyEvent event) {
    return false;
}

@Override
public boolean onKeyOther(View view, Editable text, KeyEvent event) {
    return false;
}

@Override
public void clearMetaKeyState(View view, Editable content, int states) {

}

even onKeyDown() of activity is also not working.

When I am setting InputType.TYPE_CLASS_NUMBER or InputType.TYPE_CLASS_PHONE, it is working fine.

P.S. I want to get key down ewvent for Input Type Text.

Ad

Answer

Not exactly what you asked but this is another way to accomplish it.

You can add a textChangedListener to your EditText.

editText.addTextChangedListener(new TextWatcher() {
            String text;
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if(editText.getLineCount()==2)
                {
                    text=s.toString();
                }
            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(editText.getLineCount()>2)
                {
                    editText.setText(text);
                    editText.setSelection(text.length()); //move cursor to the end of the string
                }

            }
        });
Ad
source: stackoverflow.com
Ad