Disable soft-keyboard from EditText but still allow copy/paste?

后端 未结 7 1636
误落风尘
误落风尘 2020-11-28 06:39

Hi I\'m making custom dialer so I create my own input pad.

The problem is how do I disable the EditText but still allow cut/copy/paste?

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 07:14

    I had the same problem but I also wanted later allow typing after doulbe tap.. after hours and hours I found working solution (at least for me). Use this in your onCreate method:

    editText.setCursorVisible(false);
    editText.setTextIsSelectable(true);
    editText.setShowSoftInputOnFocus(false);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);  // This just hide keyboard when activity starts
    

    These lines should definitely do the trick.. and if you want to revert that use this:

    editText.setCursorVisible(true);
    editText.setShowSoftInputOnFocus(true);
    

    To show keyboard again use:

    private void showSoftKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        view.requestFocus();
        inputMethodManager.showSoftInput(view, 0);
    }
    

    To allow copy/paste next time just use these three lines:

    editText.setCursorVisible(false);
    editText.setTextIsSelectable(true);
    editText.setShowSoftInputOnFocus(false);
    

    For further keyboard hide use:

    private void hideSoftKeyboard() {
        if(getCurrentFocus() != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
    

    This code is working on API >= 21. Hope it helps to someone

提交回复
热议问题