버튼 누름시 가상 키보드 닫기


133

나는이 Activity와 EditText, 버튼과를 ListView. 목적은에 검색 화면을 입력 EditText하고 버튼을 누르고 검색 결과가이 목록을 채우도록하는 것입니다.

이것은 모두 완벽하게 작동하지만 가상 키보드는 이상하게 작동합니다.

를 클릭하면 EditText가상 키보드가 나타납니다. 가상 키보드에서 "완료"버튼을 클릭하면 사라집니다. 그러나 가상 키보드에서 "완료"를 클릭하기 전에 검색 버튼을 클릭하면 가상 키보드가 그대로 유지되어 제거 할 수 없습니다. "완료"버튼을 클릭해도 키보드가 닫히지 않습니다. "완료"단추를 "완료"에서 화살표로 변경하고 계속 표시합니다.

당신의 도움을 주셔서 감사합니다

답변:


304
InputMethodManager inputManager = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE); 

inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                     InputMethodManager.HIDE_NOT_ALWAYS);

나는 onClick(View v)이벤트 직후에 이것을 넣었다 .

가져와야합니다 android.view.inputmethod.InputMethodManager.

버튼을 클릭하면 키보드가 숨겨집니다.


55
참고 : (포커스가없는 경우에이 메소드를 사용하려는 경우 (예 : onPause () 등) : inputManager.hideSoftInputFromWindow((null == getCurrentFocus()) ? null : getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
— Peter Ajtai

5
또한 컨텍스트를 가져와야합니다.
— Si8

4
주의 : 키보드가 이미 숨겨져 있으면 NPE가 발생합니다. 이것을 피하기 위해 Peter의 의견을 따르십시오.
— Don Larynx

관련이없는 버튼을 클릭 한 후 키보드가 나타나는 이유는 무엇입니까? 누군가 설명이나 링크를 제공 할 수 있습니까?
— kommradHomer

1
매력처럼 작동합니다!
— ARiF

59
mMyTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // hide virtual keyboard
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(m_txtSearchText.getWindowToken(), 
                                      InputMethodManager.RESULT_UNCHANGED_SHOWN);
            return true;
        }
        return false;
    }
});

그것은 나를 위해 작동합니다. 감사!
— Aman Goyal

29

아래 코드 사용

your_button_id.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try  {
            InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {

        }
    }
});

2
간단한 null 확인 대신 예외를 잡는가?
— Dr Glass

나를 위해 일하고, 버튼 클릭시 키보드를 숨 깁니다
— ashishdhiman2007

내가 필요한 것에 대한 간단한 해결책 : 검색 버튼을 클릭 한 후 키보드를 숨기십시오.
— dawoodman71

13

OnEditorActionListenerEditView를 구현해야 합니다.

public void performClickOnDone(EditView editView, final View button){
    textView.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(EditView v, int actionId, KeyEvent event) {
            hideKeyboard();
            button.requestFocus();
            button.performClick();
            return true;
        }
    });

그리고 당신은 키보드를 숨 깁니다 :

public void hideKeybord(View view) {
    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),
                                  InputMethodManager.RESULT_UNCHANGED_SHOWN);
}

또한 버튼을 사용하여 키보드 숨기기를 실행해야합니다. onClickListener

이제 가상 키보드와 버튼에서 '완료'를 클릭하면 키보드가 숨겨지고 클릭 동작이 수행됩니다.


훌륭하지만 잘 따르지 않습니다. 게시물이 코드 중 일부를 먹은 것 같습니다 (샘플에서 "공공 무효"다음에는 아무것도 없습니다). 내 활동의 onCreate 메소드에서 setOnEditorActionListner를 설정하려고 시도했지만 setOnEditorActionListener가 무엇인지 알 수 없습니다. "익명 내부 유형"알림이 표시됩니다. (내 활동 onCreate 메서드 에서이
— Andrew

1
이 코드에는 몇 가지 실수가있는 것처럼 보이지만 올바른 아이디어입니다. 우선, OnEditorActionListener 인터페이스는 내부 클래스이므로 명시 적으로 가져 오거나 (이 경우 Eclipse가 대신하지 않음)로 참조해야합니다 TextView.OnEditorActionListener.
— MatrixFrog

약간의 문제가 있습니다. onEditorActionListener를 구현했습니다 (공개 클래스 SearchActivity는 ListActivity가 OnClickListener, OnEditorActionListener를 구현합니다.) (TextView v, int actionId, KeyEvent 이벤트). 수퍼 클래스 메소드를 대체해야한다고합니다. 어떤 아이디어?
— Andrew

안녕하세요, yourEditView.setOnEditorActionListener (new OnEditorActionListener () {....를 입력하여 OnEditorActionListener를 인라인 할 수 있습니다.
— pixel

11

버튼 클릭 이벤트 내에 다음 코드를 추가하십시오.

InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

1
매력처럼 작동합니다!
— coderpc

10

편집 텍스트가 하나뿐이므로 버튼 클릭 내부에서 해당 편집 텍스트에 대해 수행 된 작업을 호출하기 만하면 나머지는 시스템에서 처리합니다. 하나 이상의 편집 텍스트가 있다면 초점을 맞춘 편집 텍스트를 먼저 가져와야하므로 그렇게 효율적이지 않습니다. 그러나 귀하의 경우에는 완벽하게 작동합니다

myedittext.onEditorAction(EditorInfo.IME_ACTION_DONE)

1
다른 사람들이 솔루션을 이해하고 배울 수 있도록 솔루션이 작동하는 이유에 대한 설명을 남길 수 있습니까? 감사!
— Shawn

숀. 자세가 명확하지 않은 경우 포즈에
— 익숙

이것이 가장 우아한 방법 중 하나라고 믿습니다. 감사합니다 @Laert
— WitVault

9

활동,

InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

단편의 경우 getActivity ()를 사용하십시오.

getActivity (). getSystemService ();

getActivity (). getCurrentFocus ();

InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);

7

이 솔루션은 나에게 완벽하게 작동합니다.

private void showKeyboard(EditText editText) {
    editText.requestFocus();
    editText.setFocusableInTouchMode(true);
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(editText, InputMethodManager.RESULT_UNCHANGED_SHOWN);
    editText.setSelection(editText.getText().length());
}

private void closeKeyboard() {
    InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
}

3

이 시도...

  1. 키보드 표시

    editText.requestFocus();
    InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
  2. 키보드 숨기기

    InputMethodManager inputManager = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE); 
    inputManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

"키보드 숨기기"방법은 너무 복잡합니다 (숨겨져 있으면 숨기기, 숨겨져 있으면 표시)
— Ninja Coding

1
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);enter code here}

안녕하세요! 이 답변의 필요 충분 수도 있지만 앤드류를 당신이 어떤 explaination 그것을 확장 할 수 미래의 독자가 그것의 최대한 혜택을 누릴 수 있음을 확인하는 경우는 좋은 것입니다!
— derM

1

코 틀린 예 :

val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

조각에서 :

inputMethodManager.hideSoftInputFromWindow(activity?.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)

활동에서 :

inputMethodManager.hideSoftInputFromWindow(currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)

0

이 코드는 버튼 클릭 이벤트에서 사용합니다

// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

0

충돌 널 포인트 예외 수정 : 사용자가 버튼을 클릭 할 때 키보드가 열리지 않는 경우가있었습니다. getCurrentFocus ()가 null이 아닌지 확인하려면 if 문을 작성해야합니다.

            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(getCurrentFocus() != null) {
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

-2

을 설정 android:singleLine="true"하면 자동으로 버튼이 키보드를 숨 깁니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.