안드로이드 해제 키보드


147

버튼을 눌렀을 때 키보드를 어떻게 닫습니까?


EditText Focusable = False로 작업을 수행하십시오. 완전히 비활성화 하시겠습니까?
st0le

답변:


325

가상 키보드를 비활성화 또는 해제 하시겠습니까?

그냥 닫으려면 버튼 클릭 이벤트에서 다음 코드 줄을 사용할 수 있습니다.

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

1
이것에 대한 두 가지 문제 .... 하나는 myEditText가 Final이어야한다는 것입니다. 두 번째는 포커스가있는 EditText 상자를 알아야한다는 것입니다. 이것에 대한 해결책?
Ethan Allen

78
여기에서 우연히 발견되는 다른 사람 은 첫 번째 인수에 대한 활동 (현재 활동 또는 조각 getActivity())을 getCurrentFocus().getWindowToken()사용할 수 hideSoftInputFromWindow()있습니다. 또한 활동을 변경할 때 사라지게하려는 경우가 onPause()아닌 onStop()작업을 수행하십시오.
Drake Clarris

2
이 답변은 여기의 의견과 함께 내 문제를 완전히 해결했습니다!
aveschini

9
키보드를 닫는 못생긴, 못생긴 방법. 앞으로는 그렇게 간단한 일을 할 수있는 더 확실한 방법이 있기를 바랍니다.
Subby

73

위의 솔루션은 모든 장치에서 작동하지 않으며 EditText를 매개 변수로 사용합니다. 이것은 내 솔루션입니다.이 간단한 방법을 호출하십시오.

private void hideSoftKeyBoard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

    if(imm.isAcceptingText()) { // verify if the soft keyboard is open                      
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

3
isAcceptingText()이 답변을 다른 사람보다 낫게 함
user1506104

좋은 해결책 ... 드문 경우이지만 키보드가 여전히 화면에있을 때 isAcceptingText ()가 false를 반환 할 수 있습니다. 예를 들어 EditText에서 선택 가능하지만 같은 창에서는 편집 할 수없는 텍스트를 클릭하십시오.
Georgie

29

이것은 나의 해결책이다

public static void hideKeyboard(Activity activity) {
    View v = activity.getWindow().getCurrentFocus();
    if (v != null) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
}

키보드를 표시 한보기를 아는 경우입니다.
RPM

16

버튼 클릭 이벤트에서이 코드를 사용할 수도 있습니다.

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

13

다음은 Kotlin 솔루션입니다 (다양한 답변을 스레드에 혼합)

확장 함수 생성 (아마도 일반적인 ViewHelpers 클래스에서)

fun Activity.dismissKeyboard() {
    val inputMethodManager = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
    if( inputMethodManager.isAcceptingText )
        inputMethodManager.hideSoftInputFromWindow( this.currentFocus.windowToken, /*flags:*/ 0)
}

그런 다음 간단히 다음을 사용하여 소비하십시오.

// from activity
this.dismissKeyboard()

// from fragment
activity.dismissKeyboard()

5

InputMethodManager가있는 첫 번째 솔루션은 나를 위해 챔피언처럼 작동했습니다 .getWindow (). setSoftInputMode 메소드는 Android 4.0.3 HTC Amaze에서 작동하지 않았습니다.

@Ethan Allen은 편집 텍스트를 최종적으로 만들 필요가 없었습니다. 아마도 포함 메소드를 선언 한 EditText 내부 클래스를 사용하고 있습니까? EditText를 Activity의 클래스 변수로 만들 수 있습니다. 또는 내부 클래스 / 메소드 안에 새 EditText를 선언하고 findViewById ()를 다시 사용하십시오. 또한 양식의 어떤 EditText에 포커스가 있는지 알아야합니다. 나는 임의로 하나를 골라서 사용할 수 있습니다. 이렇게 :

    EditText myEditText= (EditText) findViewById(R.id.anyEditTextInForm);  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

3
스택 오버플로에 오신 것을 환영합니다! 이것은 실제로 의견이 아니라 답변입니다. 조금 더 많은 담당자와 의견을 게시 할 수 있습니다 .
Jack

4
    public static void hideSoftInput(Activity activity) {
    try {
        if (activity == null || activity.isFinishing()) return;
        Window window = activity.getWindow();
        if (window == null) return;
        View view = window.getCurrentFocus();
        //give decorView a chance
        if (view == null) view = window.getDecorView();
        if (view == null) return;

        InputMethodManager imm = (InputMethodManager) activity.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null || !imm.isActive()) return;
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

1

이 솔루션은 키보드를 숨기지 않은 경우 키보드를 숨기지 않아도 아무것도하지 않도록합니다. 확장을 사용하므로 모든 컨텍스트 소유자 클래스에서 사용할 수 있습니다.


fun Context.dismissKeyboard() {
    val imm by lazy { this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }
    val windowHeightMethod = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight")
    val height = windowHeightMethod.invoke(imm) as Int
    if (height > 0) {
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
    }
}


0

관점의 맥락을 사용함으로써 Kotlin에서 다음 확장 방법으로 원하는 결과를 얻을 수 있습니다.

/**
 * Get the [InputMethodManager] using some [Context].
 */
fun Context.getInputMethodManager(): InputMethodManager {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return getSystemService(InputMethodManager::class.java)
    }

    return getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
}

/**
 * Dismiss soft input (keyboard) from the window using a [View] context.
 */
fun View.dismissKeyboard() = context
        .getInputMethodManager()
        .hideSoftInputFromWindow(
                windowToken
                , 0
        )

이것들이 제정되면 다음을 호출하십시오.

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