0

I am using search interface in one of my fragments. I want to handle "Enter KeyEvent" in the edittext of the search interface.Whenever the user presses enter in the edittext of the search I want to do something that time. I can make use of onTextSubmit() method but its not detecting the enter key press event when the edittext is empty.

But I want to handle the enter key event when the edit text is empty.Can someone help me ?

ydnas
  • 519
  • 1
  • 12
  • 29

2 Answers2

1

You can check by this:

yourEditView.setOnKeyListener(new OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                    && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Perform action on Enter key press
                if(yourEditView.isEmpty()&&yourEditView.lengh()==0){
                  // Perform your task here
                }
                return true;
            }
            return false;
        }
    });
Piyush
  • 18,895
  • 5
  • 32
  • 63
1

Here i have used both of them ,

First is for Enter Key to do some task while click on Enter.

  <EditText android:imeOptions="actionDone"
        android:inputType="text"/> 

    editText.setOnKeyListener(new OnKeyListener()
    {
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                switch (keyCode)
                {
                    case KeyEvent.KEYCODE_DPAD_CENTER:
                    case KeyEvent.KEYCODE_ENTER:
                        addCourseFromTextBox();
                        return true;
                    default:
                        break;
                }
            }
            return false;
        }
    });

Second is for Search key to search some text.

<EditText android:imeOptions="actionSearch" 
    android:inputType="text"/> 

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            performSearch();
            return true;
        }
        return false;
    }
});

Check out all imeOptions in detail.

Community
  • 1
  • 1
Chintan Khetiya
  • 15,962
  • 9
  • 47
  • 85
  • How do you get the edit text from the search interface? I am using this in my menu.xml file to have the search interface in my fragment – ydnas Dec 23 '13 at 11:52
  • I don't understand how do you get edit text like this when using an search interface. Can u explain me bit clearly? I referred this link"http://developer.android.com/training/search/setup.html" to implement my search interface. I am a newbie to android. Please help me – ydnas Dec 23 '13 at 13:09