单击设备/电话的后退按钮时如何同时隐藏键盘和按钮

时间:2018-08-24 08:50:37

标签: android back-button keyevent

单击设备/电话的后退按钮时如何隐藏键盘和按钮?

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            button.setVisibility(View.GONE);
            return true;
        }
        return false;
}

3 个答案:

答案 0 :(得分:1)

调用Activity的onBackPressed()

 @Override
 public void onBackPressed() {
 super.onBackPressed();
 public static void hideSoftKeyboard(Activity activity) {
        final InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive()) {
            if (activity.getCurrentFocus() != null) {
                inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            }
        }
    }
    }

答案 1 :(得分:1)

按下onKeyDown后,将调用下面的button方法:

public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed(); \\Method call hear
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

现在调用onBackPressed()中的隐藏键盘功能

@Override
    public void onBackPressed() {
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    .hideSoftInputFromWindow(mainLayout.getWindowToken(), 0);
    button.setVisibility(View.GONE); //Hide your button this way
    }

答案 2 :(得分:0)

步骤1:写一个隐藏软键盘的方法。

步骤2:当用户按下“返回”键时,系统将在您的活动中调用onBackPressed方法。因此,您应该将软键盘和按钮隐藏在那里。

将此添加到您的活动中:

public void hideSoftKeyboard(Context context, View view) {
        InputMethodManager imm =
                (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
}

@Override
public void onBackPressed() {
    super.onBackPressed();

    // Hide the soft keyboard
    hideSoftKeyboard(this, button);

    // Hide the button
    button.setVisibility(View.GONE);
}