Programming VIP
Very Interesting Programming
Android Dialog and the correct way to open the soft keyboard
1. Write before
The first blog in 2017, I wish you all a Happy New Year, healthy and safe in the new year!
The main content of this blog is about the display and hiding of the soft keyboard in Dialog. The requirement is to have a password input box in Dialog, pop up the Dialog display soft keyboard, turn off the hidden soft keyboard in Dialog.
Well, is it a bit simple, but there are still some problems in the process of implementation. After trying most of the methods on the Internet, I finally found a good way to share it with you.
Look at the picture:
2. Implementation process
Let’s start with the initial implementation:
But, the soft keyboard is not displayed, there are two ways to display the soft keyboard, the first way is used, the second method has no effect in Dialog.
So look at the source code of Dialog and see that the display and hiding of Dialog is handled by Handler. Is it possible that the method of displaying the soft keyboard executes too fast, so the soft keyboard is displayed delay after the show method, and it is found that it can be displayed normally.
But deferred processing is obviously not a good way to do this. Is there a way to call back once the Dialog display is complete? Well, yes, there is a setOnShowListener method that displays a soft keyboard in the callback method onShow of the OnShowListener interface.There are no limitations to hiding the soft keyboard, either after dismiss or in the callback method onDismiss.
Delayed display soft keyboard
3. Code
Show Dialog prompt box
Ways to show and hide soft keyboards
Call the method that displays the Dialog
4. Write at the end
In the frequent tests of showing and turning off Dialog, it was found that sometimes the soft keyboard would not be displayed, but there was no rule found. Students with understanding can leave comments for me.
Welcome to your classmates’comments. If you think this blog is useful for you, leave a message or click on your favorite blog.
Added by esmarts on Tue, 14 May 2019 19:57:27 +0300
Источник
Showing keyboard automatically in Android dialogs
Having the Android soft-input keyboard pop-up when a Dialog window is shown is not so straight forward as one would think. After exploring different solutions found on the web (with no success) I managed to create a solution of my own. This article is mainly a tutorial that will help you achieve the above task.
To make this easier to explain I created a small project that will be available for download at the end of the article.
The project setup is pretty simple, I have one activity with a button to show the dialog and the dialog itself (I use a custom Dialog). Without further details on how to create an Android project let’s jump straight to the interesting parts.
The Dialog
As I mentioned above I use a custom Dialog. To create a custom dialog you need to extend the Dialog class from Android. But before we get to the actual implementation I would like to talk about the layout we will use for the dialog because this is very important. The layout needs to respect 3 conditions in order to achieve the desired outcome :
- The root layout needs to have an id (you need to get a reference to this layout);
- You need a component that gets user input (most likely an EditText widget);
- You need another component that can receive focus.
Here is the layout I created for my dialog :
As you can see, the root layout has the id dlgRoot, the widget that will get user input is the EditText with the id textView1 and the component that can receive focus is the button with id button1. You will notice that the components have some attributes that you probably didn’t know about, or you don’t use them, the first attribute is found in the EditText widget, it’s called android:selectAllOnFocus and , as it name says, it selects all the content of the EditText when the component receives focus. The second attribute, witch is very important, is the android:setFocusable from the Button widget, this tells Android that the button can receive focus.
After we created this layout, we can continue with the custom dialog class implementation. The main idea of the custom Dialog class is this : you need to set focus on a component different than the one that will get user input, you need to add a FocusChangeListener on the EditText widget (this is where we will force the keyboard to pop up) and after you added the focus listener you need to request focus on the widget. To improve user experience you will also need to hide the keyboard when the dialog is closed, for this you will need a reference to your dialog’s root layout and you need to add a GlobalLayoutListener.
Let’s take a closer look at the code, you can add the following snippets either in your constructor or in the onCreate method.
We start with the button, because we need it to have focus before the EditText.
this.okBtn = (Button) findViewById(R.id.button1); this.okBtn.setOnClickListener(this); this.okBtn.requestFocus();
Notice the this.okBtn.requestFocus(), this will get the focus to the button. I also implemented the onClick listener that will just dismiss the dialog because I don’t care about a result in this demo project. Moving on to the EditText widget this is what we need :
I use the toggleSoftInput method to show/hide the keyboard because the alternative (showSoftInput() / hideSoftInputFromWindow()) didn’t work for me, it could also cause troubles if you have more than one widgets that take user input. You can see we request focus for the EditText immediately after setting the listener, this will ensure that the widget will be focused and the soft-input will be shown. Also notice the boolean variable assignment this.keyboardVisible = true, this will be important later on.
Now you have a dialog window that will automatically show the soft-input keyboard. In order to hide the keyboard when the dialog closes you will also need to add the following code :
LinearLayout rootLayout = (LinearLayout) findViewById(R.id.dlgRoot); rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() < @Override public void onGlobalLayout() < keyboardVisible = !keyboardVisible; >>);
The root layout of your dialog comes in to play and will handle the GLobalLayout events. The GlobalLayout event is triggered when the layout is changing because of a global event (for example adjusting the layout size when a soft-input keyboard is shown/hidden). The only thing we need to do here is toggle the value of keyboardVisible variable, this will in turn influence the behavior of the
onStop method, basically telling it if it needs to call the toggleSoftInput method.
Before you hide the keyboard you need to make sure it’s visible,otherwise instead of hiding you will be showing the keyboard. The alternate method hideSoftInputFromWindow() would have fixed this problem, but I couldn’t get it to work (after my EditText widget loses focus, the bind to the keyboard is lost for the current context). That was it for the custom dialog implementation, let’s also take a look at the main activity that will show this dialog.
The main activity
This is pretty much an ordinary Activity and I only want to point out 2 issues :
- always create your dialogs in the onCreateDialog method, it saves you some trouble and assures you that the dialog will be handled correctly if the user changes phone orientation.
@Override public void onDismiss(DialogInterface arg0)
That was all, you now have a dialog that will automatically pop-up a keyboard when it’s shown.
Thanks for reading, I know it’s not the cleanest solution but at least it works, as promised at the begining of the article here is the demo project .
Finally, there’s another very important peculiarity of what does Cialis that brings it so high above its alternatives. It is the only med that is available in two versions – one intended for use on as-needed basis and one intended for daily use. As you might know, Viagra and Levitra only come in the latter of these two forms and should be consumed shortly before expected sexual activity to ensure best effect. Daily Cialis, in its turn, contains low doses of Tadalafil, which allows to build its concentration up in your system gradually over time and maintain it on acceptable levels, which, consequently, makes it possible for you to enjoy sex at any moment without having to time it.
Источник
Android: показывать программную клавиатуру автоматически, когда фокус находится на EditText
Я показываю поле ввода с помощью AlertDialog . The EditText внутри самого диалога автоматически фокусируется, когда я вызываю AlertDialog.show() , но экранная клавиатура не отображается.
как сделать так, чтобы мягкая клавиатура автоматически отображалась при отображении диалога? (и нет физической/аппаратной клавиатуры). Подобно тому, как при нажатии кнопки поиска для вызова глобального поиска автоматически отображается программная клавиатура.
24 ответов
вы можете создать слушателя фокуса на EditText на AlertDialog , потом AlertDialog ‘ s Window . Оттуда вы можете сделать мягкую клавиатуру шоу, позвонив setSoftInputMode .
для показа использования клавиатуры:
для скрытия клавиатуры используйте:
вы можете запросить программную клавиатуру сразу после создания диалога (тест на SDK — r20)
У меня была такая же проблема и я решил ее со следующим кодом. Я не уверен, как он будет вести себя на телефоне с аппаратной клавиатурой.
фрагменты кода из других ответов работают, но не всегда очевидно, где их разместить в коде, особенно если вы используете AlertDialog.Builder и после официальный диалог учебник потому что он не использует final AlertDialog . или alertDialog.show() .
потому что SOFT_INPUT_STATE_ALWAYS_VISIBLE скроет клавиатуру, если фокус переключится от EditText, где SHOW_FORCED будет отображать клавиатуру, пока она явно отклоняется, даже если пользователь возвращается на рабочий стол или отображает последние приложения.
Ниже приведен рабочий код для AlertDialog, созданный с помощью пользовательского макета с EditText, определенным в XML. Он также устанавливает клавиатуру, чтобы иметь клавишу» go » и позволяет ему запускать положительную кнопку.
посмотри этой обсуждение, которое обрабатывает ручное скрытие и отображение IME. Тем не менее, я чувствую, что если сфокусированный EditText не поднимает IME, потому что вы вызываете AlertDialog.show() в своем OnCreate() или какой-то другой метод, который вызывается до того, как экран фактически представлен. Переместить его в OnPostResume() должен исправить это в этом случае, я считаю.
позвольте мне указать дополнительную информацию о решении yuku, потому что мне было трудно заставить это работать! Как получить объект AlertDialog из моего AlertDialog.Строитель? Ну, это результат моего alert.show() исполнение:
Ну, это довольно старый пост, еще есть что добавить.
эти 2 простых метода, которые помогают мне держать клавиатуру под контролем, и они работают просто отлично:
показать клавиатуру
спрятать клавиатуру
Да, вы можете сделать с setOnFocusChangeListener это поможет вам.
Если кто-то становится:
не удается сделать статическую ссылку на нестатический метод getSystemService (String) из типа Activity
попробуйте добавить контекст для вызова getSystemService.
исходный вопрос касается диалогов, и мой EditText находится на обычном представлении. В любом случае, я подозреваю, что это должно сработать и для большинства из вас. Итак, вот что работает для меня (предложенный выше метод с самым высоким рейтингом ничего не сделал для меня). Вот пользовательский EditView, который делает это (подклассы не нужны, но я нашел его удобным для моих целей, поскольку я хотел также захватить фокус, когда представление станет видимым).
это на самом деле во многом совпадает с tidbecks ответа. Я на самом деле не заметил его ответа вообще, так как у него было ноль голосов. Тогда я собирался просто прокомментировать его сообщение, но это было бы слишком долго, поэтому я закончил этот пост в любом случае. тидбек указывает, что он не уверен, как это работает с устройствами, имеющими клавиатуры. Я могу подтвердить, что поведение кажется совершенно одинаковым в любом случае. Это так, что в портретном режиме появляется программная клавиатура, а в ландшафтном-нет. Наличие физической клавиатуры выскользнуло или не делает нет разница на моем телефоне.
Источник