How to close or hide the virtual keyboard on Android?
In Android there are some situations, we should close android default keyboard forcefully. For that this example is help for you.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
Step 3Add the following code to src/MainActivity.java
In the above code when you click on the button it will hide keyboard. To hide keyboard, use the following code.
Step 5 − Add the following code to manifest file as shown below.
In the above code it contains windowSoftInputMode, it means it will show keyboard always when edit text is request focused.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Close/Hide the Soft Keyboard in Android
Preface: If you’ve read any of my Android articles, you already know how I feel about the worst SDK on Earth. This is the article that really crystallized my opinion. In my frustration, I crafted what has become the top answer on Stack Overflow for hiding the soft keyboard in Android. While I’m happy to have been of service, I do wish the SDK didn’t suck to such a degree that crafting an entire article was necessary in the first place!
How do I close or hide the soft keyboard in Android?
Simple question. INSANELY complex answer.
To help clarify the madness that follows, I’d like to begin by apologizing on behalf of all Android users for Google’s downright ridiculous treatment of the soft keyboard. The reason there are so many StackOverflow answers, each different, for the same simple question because this API, like many others in Android, is horribly designed. I can think of no polite way to state it.
I want to hide the keyboard. I expect to provide Android with the following statement:
The end. Thank you very much.
But Android has a problem. You must use the InputMethodManager to hide the keyboard. OK, fine, this is Android's API to the keyboard.
BUT! You are required to have a Context in order to get access to the IMM. Now we have a problem. I may want to hide the keyboard from a static or utility class that has no use or need for any Context . And FAR worse, the IMM requires that you specify what View (or even worse, what Window ) you want to hide the keyboard FROM.
This is what makes hiding the keyboard so challenging.
Dear Google: When I’m looking up the recipe for a cake, there is no RecipeProvider on Earth that would refuse to provide me with the recipe unless I first answer WHO the cake will be eaten by AND where it will be eaten!!
This sad story ends with the ugly truth: to hide the Android keyboard, you will be required to provide 2 forms of identification: a Context and either a View or a Window .
Hiding the keyboard from an Activity
I have created a static utility method which can do the job VERY solidly, provided you call it from an Activity .
Be aware that this utility method ONLY works when called from an Activity ! The above method calls getCurrentFocus of the target Activity to fetch the proper window token.
Hiding the keyboard from a Fragment
But suppose you want to hide the keyboard from an EditText hosted in a DialogFragment ? You can't use the method above for that:
This won’t work because you’ll be passing a reference to the Fragment 's host Activity , which will have no focused control while the Fragment is shown! Wow!
So, for hiding the keyboard from fragments, I resort to the lower-level, more common, and uglier:
Below is some additional information gleaned from more time wasted chasing this solution.
About `windowSoftInputMode`
There’s yet another point of contention to be aware of. By default, Android will automatically assign initial focus to the first EditText or focusable control in your Activity . It naturally follows that the InputMethod (typically the soft keyboard) will respond to the focus event by showing itself. The windowSoftInputMode attribute in AndroidManifest.xml , when set to stateAlwaysHidden , instructs the keyboard to ignore this automatically-assigned initial focus.
Almost unbelievably, it appears to do nothing to prevent the keyboard from opening when you touch the control (unless focusable="false" and/or focusableInTouchMode="false" are assigned to the control). Apparently, the windowSoftInputMode setting applies only to automatic focus events, not to focus events triggered by touch events.
Therefore, stateAlwaysHidden is VERY poorly named indeed. It should perhaps be called ignoreInitialFocus instead.
More ways to get a window token
If there is no focused view (e.g. can happen if you just changed fragments), there are other views that will supply a useful window token.
These are alternatives for the above code if (view == null) view = new View(activity); These don't refer explicitly to your activity.
Inside a fragment class:
Given a fragment fragment as a parameter:
Starting from your content body:
One more tidbit: clear focus to avoid showing keyboard again if you open the app from the background, by adding this line to the end of the method:
Android studio как убрать клавиатуру
Completing the CAPTCHA proves you are a human and gives you temporary access to the web property.
What can I do to prevent this in the future?
If you are on a personal connection, like at home, you can run an anti-virus scan on your device to make sure it is not infected with malware.
If you are at an office or shared network, you can ask the network administrator to run a scan across the network looking for misconfigured or infected devices.
Another way to prevent getting this page in the future is to use Privacy Pass. You may need to download version 2.0 now from the Chrome Web Store.
Cloudflare Ray ID: 71aef69f3b2771c2 • Your IP : 82.102.23.104 • Performance & security by Cloudflare
[Перевод] Как закрыть/скрыть программную клавиатуру в Android
От переводчика: без шуток, а можно было бы создать более простое решение для такой казалось бы простой и частой задачи.
Предисловие: Если вы читали какую-либо из моих статей по Android, то уже знаете, что я думаю о худшем SDK на Земле (английский). Эта статья только укрепила это мнение. К моему разочарованию, я создал то, что стало топ ответом Stack Overflow в вопросе по поводу сокрытия клавиатуры в Android. И хоть я и счастлив, что был полезен. Но так же я бы хотел, чтобы SDK не был таким отстойным и не требовало написания целой статьи для подобного.
Как закрыть или скрыть программную клавиатуру в Android?
Вопрос простой. БЕЗУМНО сложный ответ.
Чтобы помочь прояснить последующее безумия, я бы хотел извиниться от имени всех пользователей Android за отвратительное отношение Google к программной клавиатуре. Причина, по которой на простой вопрос StackOverflow есть так много разных ответов — ужасный дизайн этого API (как и многих других в Android). Не смог придумать как это сказать мягче.
Я хочу спрятать клавиатуру. Я ожидаю, что Android предоставит что-то вроде: Keyboard.hide()
Но у Android есть проблема. Вы должны использовать для этого InputMethodManager. ОК, ладно, это Android API для клавиатуры.
НО! Вам так же нужно иметь Context для доступа к IMM. Вот теперь у нас проблема. Возможно я хочу скрыть клавиатуру из статического или вспомогательного класса, которые не используют и не нуждаются ни в каких Context. Но еще хуже то, что IMM требует от вас указать для какого View (или того хуже Window) вы хотите скрыть клавиатуру.
Это и делает из простой операции целое испытание.
Дорогой Google: Когда я ищу рецепт торта, то нет на Земле никакого RecipeProvider, который откажет в выдаче рецепта, пока я не укажу КТО будет есть этот торт и ГДЕ он будет это делать.
Скрываем клавиатуру из Activity
Я создал статическую функцию, которая надежно выполняет эту задачу (если вы вызываете её из Activity).
Прим. в оригинале используют Java, но у меня все проекты уже на Kotlin, да и язык сейчас все популярнее, а потому добавлю немного измененный аналогичный код.