简体   繁体   中英

Show keyboard after pressing a button

I have clear button to clear EditText.

<Button
        android:id="@+id/bClearText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right|center_vertical"
        android:layout_marginRight="10dp"
        android:onClick="clearEtSearch"
        android:background="@drawable/delete" />

This method clears EditText:

    public void clearEtSearch(View v) {
    etSearch.setText("");
    etSearch.requestFocus();
    showKeyboard(etSearch);
}

I have taken code below from hiding and changed to show keyboard, but it is not working

    private void showKeyboard(View view) {
    InputMethodManager manager = (InputMethodManager) view.getContext()
            .getSystemService(INPUT_METHOD_SERVICE);
    if (manager != null)
        manager.showSoftInputFromInputMethod(view.getWindowToken(), 0);
}

What I am doing wrong? Please give suggestions to correct my code.

I'm not sure but you can try to use Context.INPUT_METHOD_SERVICE instead of just INPUT_METHOD_SERVICE . Some are Forcing the Soft Keyboard open question for more.

You can also see How to show soft-keyboard when edittext is focused See if following works:

public void clearEtSearch(View v) {
    etSearch.setText("");
    etSearch.requestFocus();

    InputMethodManager manager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);    
    manager.showSoftInputFromInputMethod(etSearch.getWindowToken(), 0);

}

Depending on your need you may try different constants of InputMethodManager like following:

public void clearEtSearch(View v) {
    etSearch.setText("");
    etSearch.requestFocus();
    InputMethodManager manager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);    
    manager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}

or

public void clearEtSearch(View v) {
    etSearch.setText("");
    etSearch.requestFocus();
    InputMethodManager manager= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    manager.showSoftInput(etSearch, InputMethodManager.SHOW_FORCED);
}

I haven't tried the code right not so not sure which one would work. See There are many related questions. Hope it works well for you.

Use this method and enjoy

public void showSoftKeyboard() {
        try {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.SHOW_FORCED, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM