androidvalidationandroid-edittextandroid-softkeyboardonkeylistener

not able to perform OnKeyListener correctly


I want to apply few number validation after entering text into edit-text.I tried to do it using TextWatcher, but it works properly on high versions only , not in lower version.

Hence I want to use OnKeyListener events. But that is also not working.

start_time_edit.setOnKeyListener(onSoftKeyboardDonePress);

private View.OnKeyListener onSoftKeyboardDonePress=new View.OnKeyListener()
{
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {

        if (event.getKeyCode() == KeyEvent.ACTION_DOWN)
        {
            Toast.makeText(CreateTimesheet.this, "checking event", Toast.LENGTH_LONG).show();
        }

        return false;
    }
};

It never goes inside the If statement as it both the values doesn't match.

What should I do?


Solution

  • You can also use setOnEditorActionListener instead of setOnKeyListener on EditText.

    Here is sample code, please try it.

    start_time_edit.setImeActionLabel("Next", KeyEvent.KEYCODE_ENTER);
    start_time_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    
                @Override
                public boolean onEditorAction(TextView arg0, int actionId, KeyEvent event) {
                    if ((event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        Toast.makeText(CreateTimesheet.this, "checking event", Toast.LENGTH_LONG).show();
                    }
                    return false;
                }
            });