2015年11月6日 星期五

Add search button on keyboard and close the keyboard when click the search button

Reference:
http://stackoverflow.com/questions/3205339/android-how-to-make-keyboard-enter-button-say-search-and-handle-its-click
http://stackoverflow.com/questions/23528644/edittext-ignores-the-imeactionlabel
http://stackoverflow.com/questions/3400028/close-virtual-keyboard-on-button-press
http://stackoverflow.com/questions/13593069/androidhide-keyboard-after-button-click

Code snippet:
layout.xml

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

class.java

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

            // close the keyboard
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                      InputMethodManager.RESULT_UNCHANGED_SHOWN);
            return true;
        }
        return false;
    }
});

沒有留言: