etc./StackOverFlow

프로그래밍 방식으로 Android 소프트 키보드를 닫거나 숨기는 방법은 무엇입니까?

청렴결백한 만능 재주꾼 2021. 10. 1. 03:18
반응형

질문자 :Community Wiki


내 레이아웃에 EditTextButton

편집 필드에 작성하고 Button 클릭한 후 키보드 외부를 터치할 때 가상 키보드를 숨기고 싶습니다. 나는 이것이 간단한 코드 조각이라고 가정하지만, 어디에서 그 예를 찾을 수 있습니까?



당신은 사용하여 가상 키보드 숨기기 위해 안드로이드를 강제 할 수 InputMethodManager를 호출 hideSoftInputFromWindow 당신의 초점 뷰를 포함하는 윈도우의 토큰을 전달합니다.

 // 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); }

이렇게 하면 모든 상황에서 키보드가 숨겨집니다. 어떤 경우에는 InputMethodManager.HIDE_IMPLICIT_ONLY 를 두 번째 매개변수로 전달하여 사용자가 (메뉴를 길게 눌러) 명시적으로 강제로 나타내지 않았을 때만 키보드를 숨길 수 있도록 하고 싶을 것입니다.

참고: Kotlin에서 이 작업을 수행하려면 다음을 사용하십시오. context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

코틀린 구문

 // Only runs if there is a view that is currently focused this.currentFocus?.let { view -> val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager imm?.hideSoftInputFromWindow(view.windowToken, 0) }

Community Wiki

이 광기를 명확히 하기 위해, 나는 구글이 소프트 키보드를 완전히 터무니없이 취급한 것에 대해 모든 Android 사용자를 대신하여 사과하는 것으로 시작하고 싶습니다. 동일한 간단한 질문에 대해 각기 다른 답변이 너무 많은 이유는 Android의 다른 많은 API와 마찬가지로 이 API가 끔찍하게 설계되었기 때문입니다. 나는 그것을 표현하는 공손한 방법이 생각나지 않는다.

키보드를 숨기고 싶습니다. Keyboard.hide() 문을 제공할 것으로 예상합니다. 끝. 매우 감사합니다. 하지만 안드로이드에는 문제가 있습니다. 키보드를 숨기려면 InputMethodManager 를 사용해야 합니다. 좋습니다. 이것은 키보드에 대한 Android의 API입니다. 하지만! IMM에 액세스하려면 Context 가 필요합니다. 이제 문제가 있습니다. Context 를 사용하지 않거나 필요로 하지 않는 정적 또는 유틸리티 클래스에서 키보드를 숨기고 싶을 수 있습니다. 또는 훨씬 더 나쁜 것은 IMM에서 키보드를 숨길 View (또는 더 나쁘게는 Window )를 지정해야 한다는 것입니다.

이것이 키보드를 숨기는 것을 어렵게 만드는 이유입니다. Dear Google: 내가 케이크 레시피를 검색할 때 내가 먼저 케이크를 누구가 먹고 어디에서 케이크를 먹을지 대답하지 않는 한 레시피 제공을 거부하는 RecipeProvider

이 슬픈 이야기는 추악한 진실로 끝납니다. Android 키보드를 숨기려면 Context View 또는 Window 두 가지 식별 형식을 제공해야 합니다.

Activity 에서 호출하면 매우 견고하게 작업을 수행할 수 있는 정적 유틸리티 메서드를 만들었습니다.

 public static void hideKeyboard(Activity activity) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); //Find the currently focused view, so we can grab the correct window token from it. View view = activity.getCurrentFocus(); //If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = new View(activity); } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }

Activity 에서 호출될 때만 작동합니다! 위의 메서드는 적절한 창 토큰을 가져오기 위해 대상 Activity getCurrentFocus

DialogFragment 에서 호스팅 EditText 에서 키보드를 숨기고 싶다고 가정해 봅시다. 위의 방법을 사용할 수 없습니다.

 hideKeyboard(getActivity()); //won't work

Fragment 가 표시되는 동안 집중 제어가 없는 Fragment 의 호스트 Activity 대한 참조를 전달하기 때문에 이것은 작동하지 않습니다! 우와! 따라서 조각에서 키보드를 숨기기 위해 더 낮은 수준의 더 일반적이고 못생긴 것에 의존합니다.

 public static void hideKeyboardFrom(Context context, View view) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }

다음은 이 솔루션을 찾는 데 더 많은 시간을 낭비하면서 얻은 몇 가지 추가 정보입니다.

windowSoftInputMode 정보

알아야 할 또 다른 논쟁점이 있습니다. Activity EditText 또는 focusable 컨트롤에 초기 포커스를 자동으로 할당합니다. 자연스럽게 InputMethod(일반적으로 소프트 키보드)가 자체적으로 표시하여 포커스 이벤트에 응답합니다. windowSoftInputMode 의 속성 AndroidManifest.xml 로 설정하면, stateAlwaysHidden 이 자동으로 할당 된 초기 초점을 무시하는 키보드를 지시합니다.

 <activity android:name=".MyActivity" android:windowSoftInputMode="stateAlwaysHidden"/>

거의 믿을 수 없을 정도로, 컨트롤을 터치할 때 키보드가 열리는 것을 방지하기 위해 아무 일도 하지 않는 것으로 보입니다( focusable="false" 및/또는 focusableInTouchMode="false" 가 컨트롤에 할당되지 않는 한). 분명히 windowSoftInputMode 설정은 터치 이벤트에 의해 트리거된 포커스 이벤트가 아니라 자동 포커스 이벤트에만 적용됩니다.

따라서 stateAlwaysHidden 은 실제로 이름이 매우 좋지 않습니다. ignoreInitialFocus 라고 해야 합니다.


업데이트: 창 토큰을 얻는 더 많은 방법

포커스된 보기가 없는 경우(예: 방금 조각을 변경한 경우 발생할 수 있음) 유용한 창 토큰을 제공하는 다른 보기가 있습니다.

다음은 위의 코드에 대한 대안입니다. if (view == null) view = new View(activity); 이들은 귀하의 활동을 명시적으로 참조하지 않습니다.

프래그먼트 클래스 내부:

 view = getView().getRootView().getWindowToken();

fragment 이 매개변수로 주어졌을 때:

 view = fragment.getView().getRootView().getWindowToken();

콘텐츠 본문에서 시작:

 view = findViewById(android.R.id.content).getRootView().getWindowToken();

업데이트 2: 백그라운드에서 앱을 열 때 키보드가 다시 표시되지 않도록 포커스를 지우세요.

메서드 끝에 다음 줄을 추가합니다.

view.clearFocus();


Community Wiki

소프트 키보드를 숨기는 데에도 유용합니다.

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

이것은 사용자가 실제로 editText 보기를 터치할 때까지 소프트 키보드를 억제하는 데 사용할 수 있습니다.


Community Wiki

키보드를 숨기는 솔루션이 하나 더 있습니다.

 InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

HIDE_IMPLICIT_ONLY 위치에 showFlag 전달하고 0hiddenFlag 합니다. 소프트 키보드를 강제로 닫습니다.


Community Wiki

Meier의 솔루션은 저에게도 효과적입니다. 제 경우에는 앱의 최상위 수준이 탭 호스트이고 탭을 전환할 때 키워드를 숨기고 싶습니다. 탭 호스트 보기에서 창 토큰을 가져옵니다.

 tabHost.setOnTabChangedListener(new OnTabChangeListener() { public void onTabChanged(String tabId) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(tabHost.getApplicationWindowToken(), 0); } }

Community Wiki

onCreate() 에서 아래 코드를 시도하십시오.

 EditText edtView = (EditText) findViewById(R.id.editTextConvertValue); edtView.setInputType(InputType.TYPE_NULL);

Community Wiki

업데이트: 이 솔루션이 더 이상 작동하지 않는 이유를 모르겠습니다(방금 Android 23에서 테스트했습니다). 대신 Saurabh Pareek 의 솔루션을 사용하십시오. 여기있어:

 InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); //Hide: imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); //Show imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

이전 답변:

 //Show soft-keyboard: getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); //hide keyboard : getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Community Wiki

protected void hideSoftKeyboard(EditText input) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(input.getWindowToken(), 0); }

Community Wiki

여기에 있는 다른 모든 답변이 원하는 대로 작동하지 않는 경우 키보드를 수동으로 제어하는 다른 방법이 있습니다.

EditText 의 속성 중 일부를 관리하는 함수를 만듭니다.

 public void setEditTextFocus(boolean isFocused) { searchEditText.setCursorVisible(isFocused); searchEditText.setFocusable(isFocused); searchEditText.setFocusableInTouchMode(isFocused); if (isFocused) { searchEditText.requestFocus(); } }

그런 다음 키보드를 열거나 닫은 EditText onFocus가 다음과 같은지 확인합니다.

 searchEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (v == searchEditText) { if (hasFocus) { // Open keyboard ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(searchEditText, InputMethodManager.SHOW_FORCED); } else { // Close keyboard ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(searchEditText.getWindowToken(), 0); } } } });

이제 키보드를 수동으로 열 때마다 다음을 호출하십시오.

 setEditTextFocus(true);

통화 종료:

 setEditTextFocus(false);

Community Wiki

Saurabh Pareek 은 지금까지 최고의 답변을 가지고 있습니다.

그러나 올바른 플래그를 사용할 수도 있습니다.

 /* hide keyboard */ ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE)) .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); /* show keyboard */ ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE)) .toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);

실제 사용 예

 /* click button */ public void onClick(View view) { /* hide keyboard */ ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE)) .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); /* start loader to check parameters ... */ } /* loader finished */ public void onLoadFinished(Loader<Object> loader, Object data) { /* parameters not valid ... */ /* show keyboard */ ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE)) .toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); /* parameters valid ... */ }

Community Wiki

검색에서 여기에서 나에게 맞는 답변을 찾았습니다.

 // Show soft-keyboard: InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); // Hide soft-keyboard: getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Community Wiki

짧은 대답

당신에서 OnClick 리스너 부르는 onEditorActionEditTextIME_ACTION_DONE

 button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { someEditText.onEditorAction(EditorInfo.IME_ACTION_DONE) } });

드릴다운

이 방법이 더 좋고 간단하며 Android의 디자인 패턴에 더 적합하다고 생각합니다. 위의 간단한 예에서(일반적으로 대부분의 일반적인 경우) EditText 가 있으며 일반적으로 처음에 키보드를 호출하는 것이기도 합니다(확실히 다음에서 호출할 수 있습니다. 많은 일반적인 시나리오). 같은 방식으로 키보드를 놓는 것이 ImeAction 으로 수행할 수 있습니다. android:imeOptions="actionDone" 하여 EditText 가 어떻게 작동하는지 확인하십시오. 동일한 방법으로 동일한 작동을 달성하기를 원할 것입니다.


이 관련 답변을 확인하십시오


Community Wiki

이것은 작동해야 합니다:

 public class KeyBoard { public static void show(Activity activity){ InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show } public static void hide(Activity activity){ InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide } public static void toggle(Activity activity){ InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); if (imm.isActive()){ hide(activity); } else { show(activity); } } } KeyBoard.toggle(activity);

Community Wiki

사용자 지정 키보드를 사용하여 16진수를 입력하고 있으므로 IMM 키보드를 표시할 수 없습니다...

v3.2.4_r1에서 setSoftInputShownOnFocus(boolean show) 가 날씨를 제어하거나 TextView에 포커스가 있을 때 키보드를 표시하지 않도록 추가되었지만 여전히 숨겨져 있으므로 반사를 사용해야 합니다.

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { try { Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class); method.invoke(mEditText, false); } catch (Exception e) { // Fallback to the second method } }

ViewTreeObserver 를 사용하여 추가 OnGlobalLayoutListener 사용하여 매우 좋은 결과를 얻었지만(완벽하지는 않음) 키보드가 다음과 같이 표시되는지 확인합니다.

 @Override public void onGlobalLayout() { Configuration config = getResources().getConfiguration(); // Dont allow the default keyboard to show up if (config.keyboardHidden != Configuration.KEYBOARDHIDDEN_YES) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mRootView.getWindowToken(), 0); } }

이 마지막 솔루션은 키보드를 몇 초 동안 표시하고 선택 핸들을 엉망으로 만들 수 있습니다.

키보드에서 전체 화면으로 들어가면 onGlobalLayout이 호출되지 않습니다. 이를 방지하려면 TextView#setImeOptions(int) 또는 TextView XML 선언을 사용하십시오.

 android:imeOptions="actionNone|actionUnspecified|flagNoFullscreen|flagNoExtractUi"

업데이트: 키보드를 표시하지 않고 모든 버전에서 작동하는 대화 상자를 방금 찾았습니다.

 getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

Community Wiki

public void setKeyboardVisibility(boolean show) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if(show){ imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); }else{ imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0); } }

Community Wiki

나는 스레드에 게시된 모든 솔루션을 통해 작업하는 데 이틀 이상을 보냈고 어떤 방식으로든 부족함을 발견했습니다. 내 정확한 요구 사항은 100% 신뢰성으로 화면 키보드를 표시하거나 숨길 수 있는 버튼을 갖는 것입니다. 키보드가 숨겨진 상태일 때 사용자가 어떤 입력 필드를 클릭하더라도 다시 나타나지 않아야 합니다. 그것이 보이는 상태에 있을 때 키보드는 사용자가 어떤 버튼을 클릭하더라도 사라지지 않아야 합니다. 이것은 최신 기기까지 Android 2.2 이상에서 작동해야 합니다.

내 앱 clean RPN 에서 이에 대한 작업 구현을 볼 수 있습니다.

여러 휴대전화(froyo 및 진저브레드 기기 포함)에서 제안된 답변을 테스트한 후 Android 앱이 안정적으로 다음을 수행할 수 있음이 분명해졌습니다.

  1. 키보드를 일시적으로 숨깁니다. 사용자가 새 텍스트 필드에 포커스를 맞추면 다시 나타납니다.
  2. 활동이 시작될 때 키보드를 표시하고 키보드가 항상 표시되어야 함을 나타내는 활동에 플래그를 설정합니다. 이 플래그는 활동이 초기화 중일 때만 설정할 수 있습니다.
  3. 키보드 사용을 표시하지 않거나 허용하지 않도록 활동을 표시합니다. 이 플래그는 활동이 초기화 중일 때만 설정할 수 있습니다.

나를 위해 일시적으로 키보드를 숨기는 것만으로는 충분하지 않습니다. 일부 장치에서는 새 텍스트 필드에 초점을 맞추는 즉시 다시 나타납니다. 내 앱이 한 페이지에 여러 텍스트 필드를 사용하기 때문에 새 텍스트 필드에 초점을 맞추면 숨겨진 키보드가 다시 팝업됩니다.

불행히도 목록의 항목 2와 3은 활동이 시작될 때만 안정성을 작동합니다. 활동이 표시되면 키보드를 영구적으로 숨기거나 표시할 수 없습니다. 트릭은 사용자가 키보드 토글 버튼을 누를 때 실제로 활동을 다시 시작하는 것입니다. 내 앱에서 사용자가 키보드 토글 버튼을 누르면 다음 코드가 실행됩니다.

 private void toggleKeyboard(){ if(keypadPager.getVisibility() == View.VISIBLE){ Intent i = new Intent(this, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); Bundle state = new Bundle(); onSaveInstanceState(state); state.putBoolean(SHOW_KEYBOARD, true); i.putExtras(state); startActivity(i); } else{ Intent i = new Intent(this, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); Bundle state = new Bundle(); onSaveInstanceState(state); state.putBoolean(SHOW_KEYBOARD, false); i.putExtras(state); startActivity(i); } }

이렇게 하면 현재 활동의 상태가 번들에 저장된 다음 활동이 시작되어 키보드를 표시할지 숨길지 나타내는 부울을 전달합니다.

onCreate 메서드 내에서 다음 코드가 실행됩니다.

 if(bundle.getBoolean(SHOW_KEYBOARD)){ ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(newEquationText,0); getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } else{ getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); }

소프트 키보드가 표시되어야 하는 경우 InputMethodManager는 키보드를 표시하고 소프트 입력을 항상 표시하도록 창에 지시합니다. 소프트 키보드를 숨겨야 하는 경우 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM이 설정됩니다.

이 접근 방식은 Android 2.2를 실행하는 4년 된 HTC 전화부터 4.2.2를 실행하는 nexus 7까지 제가 테스트한 모든 장치에서 안정적으로 작동합니다. 이 접근 방식의 유일한 단점은 뒤로 버튼을 다룰 때 주의해야 한다는 것입니다. 내 앱에는 기본적으로 하나의 화면(계산기)만 있으므로 onBackPressed()를 재정의하고 장치 홈 화면으로 돌아갈 수 있습니다.


Community Wiki

이 모든 솔루션 에 대한 대안으로 , 키보드를 여는 데 사용된 (EditText) 필드에 대한 참조 없이 어디에서나 소프트 키보드를 닫고 싶지만 필드에 포커스가 있는 경우 여전히 수행하려는 경우 다음을 사용할 수 있습니다. 이것은 (활동에서):

 if (getCurrentFocus() != null) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); }

Community Wiki

이 SO 답변 덕분에 내 경우에는 ViewPager 조각을 스크롤할 때 잘 작동하는 다음을 파생했습니다.

 private void hideKeyboard() { // Check if no view has focus: View view = this.getCurrentFocus(); if (view != null) { InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } private void showKeyboard() { // Check if no view has focus: View view = this.getCurrentFocus(); if (view != null) { InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); } }

Community Wiki

위의 답변은 다른 시나리오에서 작동하지만 보기 내부에 키보드를 숨기고 올바른 컨텍스트를 얻기 위해 고군분투하는 경우 다음을 시도하십시오.

 setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { hideSoftKeyBoardOnTabClicked(v); } } private void hideSoftKeyBoardOnTabClicked(View v) { if (v != null && context != null) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }

컨텍스트를 얻으려면 생성자에서 가져옵니다. :)

 public View/RelativeLayout/so and so (Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.context = context; init(); }

Community Wiki

유닛 또는 기능 테스트 중에 소프트 키보드를 닫고 싶다면 테스트에서 "뒤로 버튼"을 클릭하면 됩니다.

 // Close the soft keyboard from a Test getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);

위의 내용이 해당 활동에 대해 onBackPressed() 를 트리거하지 않기 때문에 "뒤로 버튼"을 따옴표로 묶었습니다. 그것은 단지 키보드를 닫습니다.

뒤로 버튼을 닫는 데 약간의 시간이 걸리므로 계속하기 전에 잠시 일시 중지해야 합니다. 따라서 보기 등에 대한 후속 클릭은 짧은 일시 중지(1초는 충분히 긴 시간)가 될 때까지 등록되지 않습니다 ).


Community Wiki

Android용 Mono(일명 MonoDroid)에서 수행하는 방법은 다음과 같습니다.

 InputMethodManager imm = GetSystemService (Context.InputMethodService) as InputMethodManager; if (imm != null) imm.HideSoftInputFromWindow (searchbox.WindowToken , 0);

Community Wiki

이것은 모든 기괴한 키보드 동작에 대해 저에게 효과적이었습니다.

 private boolean isKeyboardVisible() { Rect r = new Rect(); //r will be populated with the coordinates of your view that area still visible. mRootView.getWindowVisibleDisplayFrame(r); int heightDiff = mRootView.getRootView().getHeight() - (r.bottom - r.top); return heightDiff > 100; // if more than 100 pixels, its probably a keyboard... } protected void showKeyboard() { if (isKeyboardVisible()) return; InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (getCurrentFocus() == null) { inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } else { View view = getCurrentFocus(); inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_FORCED); } } protected void hideKeyboard() { if (!isKeyboardVisible()) return; InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); View view = getCurrentFocus(); if (view == null) { if (inputMethodManager.isAcceptingText()) inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0); } else { if (view instanceof EditText) ((EditText) view).setText(((EditText) view).getText().toString()); // reset edit text bug on some keyboards bug inputMethodManager.hideSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }

Community Wiki

간단하고 사용하기 쉬운 방법으로 hideKeyboardFrom(YourActivity.this); 키보드를 숨기려면

 /** * This method is used to hide keyboard * @param activity */ public static void hideKeyboardFrom(Activity activity) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); }

Community Wiki

매니페스트 파일의 android:windowSoftInputMode="stateHidden" 활동에 추가합니다. 예시:

 <activity android:name=".ui.activity.MainActivity" android:label="@string/mainactivity" android:windowSoftInputMode="stateHidden"/>

Community Wiki

오픈 키보드의 경우:

 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(edtView, InputMethodManager.SHOW_IMPLICIT);

키보드 닫기/숨기기:

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

Community Wiki

활동에서 이 최적화된 코드를 사용하세요.

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

Community Wiki

EditText AlertDialog 에도 있는 경우가 있으므로 키보드는 닫을 때 닫아야 합니다. 다음 코드는 어디에서나 작동하는 것 같습니다.

 public static void hideKeyboard( Activity activity ) { InputMethodManager imm = (InputMethodManager)activity.getSystemService( Context.INPUT_METHOD_SERVICE ); View f = activity.getCurrentFocus(); if( null != f && null != f.getWindowToken() && EditText.class.isAssignableFrom( f.getClass() ) ) imm.hideSoftInputFromWindow( f.getWindowToken(), 0 ); else activity.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN ); }

Community Wiki

매번 매직 터치처럼 작동

 private void closeKeyboard() { InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } private void openKeyboard() { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); if(imm != null){ imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); } }

Community Wiki

Extension Function 통한 Kotlin Version

kotlin 확장 기능을 사용하면 소프트 키보드를 표시하고 숨기는 것이 매우 간단합니다.

ExtensionFunctions.kt

 import android.app.Activity import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.fragment.app.Fragment fun Activity.hideKeyboard(): Boolean { return (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow((currentFocus ?: View(this)).windowToken, 0) } fun Fragment.hideKeyboard(): Boolean { return (context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow((activity?.currentFocus ?: View(context)).windowToken, 0) } fun EditText.hideKeyboard(): Boolean { return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(windowToken, 0) } fun EditText.showKeyboard(): Boolean { return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager) .showSoftInput(this, 0) }

• 용법

이제 Activity 또는 Fragment 에서 hideKeyboard() 에 명확하게 액세스할 수 있을 뿐만 아니라 다음과 같은 EditText

 editText.hideKeyboard()

Community Wiki

11년 만에 공식적으로 지원해 주신 하나님께 감사드립니다.

먼저 앱 gradle에 종속성 implementation 'androidx.core:core-ktx:1.6.0-beta01' 을 추가합니다.

 fun View.showKbd() { (this.context as? Activity)?.let { it.showKbd() } } fun View.hideKbd() { (this.context as? Activity)?.let { it.hideKbd() } } fun Fragment.showKbd() { activity?.let { it.showKbd() } } fun Fragment.hideKbd() { activity?.let { it.hideKbd() } } fun Context.showKbd() { (this as? Activity)?.let { it.showKbd() } } fun Context.hideKbd() { (this as? Activity)?.let { it.hideKbd() } } fun Activity.showKbd(){ WindowInsetsControllerCompat(window, window.decorView).show(WindowInsetsCompat.Type.ime()) } fun Activity.hideKbd(){ WindowInsetsControllerCompat(window, window.decorView).hide(WindowInsetsCompat.Type.ime()) }

Community Wiki

출처 : 여기를 클릭하세요


출처 : http:www.stackoverflow.com/questions/1109022/how-do-you-close-hide-the-android-soft-keyboard-programmatically

반응형