我正在使用Contextual ActionBar进行编辑,当我显示了键盘并且想通过按硬件后退按钮将其隐藏时,它隐藏了键盘,但同时也取消了上下文操作栏,我真的找不到方法继续。

任何人?

最佳答案

您应该尝试覆盖Back Key硬件,并使用boolean处理预期的行为,如下所示:

// boolean isVisible to retrieve the state of the SoftKeyboard
private boolean isVisible = false;

// isVisible becomes 'true' if the user clicks on EditText

// then, if the user press the back key hardware, handle it:
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // check isVisible
        if(isVisible) {
            // hide the keyboard
            InputMethodManager mImm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            mImm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            isVisible = false;
        } else {
            // remove the CAB
            mActionMode.finish();
        }
    }
    return false;
}


另一个解决方案可能是调用dispatchKeyEvent方法,当显示CAB时仍会调用该方法:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
        // check CAB active and isVisible softkeyboard
        if(mActionModeIsActive && isVisible) {
            InputMethodManager mImm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            mImm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            isVisible = false;
            return true;
        // Maybe you might do not call the 'else' condition, anyway..
        } else {
            mActionMode.finish();
            return true;
        }
    }
    return super.dispatchKeyEvent(event);
}


这应该可以解决问题,但我尚未对其进行测试。希望这可以帮助。
来源:How to Override android's back key when softkeyboard is open-Prevent to cancel Action Mode by press back button

10-04 23:27
查看更多