Android - requestFocus关闭键盘

时间:2014-07-21 15:48:38

标签: java android android-layout

当用户在键盘上按Enter键时,我将焦点从一个AutoCompleteTextView切换到另一个。问题是当下一个AutoCompleteTextView获得焦点时键盘始终隐藏。有什么方法可以阻止这种情况吗? 这是我用来切换焦点的代码:

field1.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_ENTER) {
                        field1.dismissDropDown();
                        field2.requestFocus();

                        return true;
                    }
                    return false;
                }
            });

我还没有在声明field1和field2的XML文件中使用任何imeOptions。

4 个答案:

答案 0 :(得分:1)

是的,切换焦点会使键盘消失。快速解决方法是以编程方式告诉键盘保持可见:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

答案 1 :(得分:0)

尝试在requestfocus()

之后以编程方式显示键盘
InputMethodManager keyboard = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
//to show keyboard
keyboard.showSoftInput(field2, 0);

//to hide keyboard
imm.hideSoftInputFromWindow(field2.getWindowToken(), 0); 

答案 2 :(得分:0)

根据AutoCompleteTextView的源代码:

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        // Perform validation if the view is losing focus.
        if (!focused) {
            performValidation();
        }
        if (!focused && !mPopup.isDropDownAlwaysVisible()) {
            dismissDropDown();
        }
    }

我认为你可以删除#field1.dismissDropDown()行 - 也许它会对你有帮助。

此外,我认为你应该设置OnEditorActionListener而不是OnKeyListener。我建议你尝试上面的代码:

  field1.setOnEditorActionListener(new AutoCompleteTextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
      if (actionId == EditorInfo.IME_ACTION_ENTER) {
        field2.requestFocus();
        return true;
      }
      return false;
    }
  });

答案 3 :(得分:0)

强行开启:

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

关闭:

((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(_pay_box_helper.getWindowToken(), 0);