Como descartar o teclado quando um botão é pressionado?
Como descartar o teclado quando um botão é pressionado?
Respostas:
Deseja desativar ou descartar um teclado virtual?
Se você quiser apenas descartá-lo, poderá usar as seguintes linhas de código nos botões, no clique em Evento
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
getActivity()) getCurrentFocus().getWindowToken()para o primeiro argumento hideSoftInputFromWindow(). Além disso, faça isso no onPause()e não no onStop()se você estiver tentando fazê-lo desaparecer ao alterar as atividades.
A solução acima não funciona para todos os dispositivos e, além disso, está usando o EditText como parâmetro. Esta é a minha solução, basta chamar este método simples:
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);
}
}
isAcceptingText()fez esta resposta melhor do que outros
Esta é a minha solução
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);
}
}
Aqui está uma solução Kotlin (misturando as várias respostas em um tópico)
Crie uma função de extensão (talvez em uma classe comum do ViewHelpers)
fun Activity.dismissKeyboard() {
val inputMethodManager = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
if( inputMethodManager.isAcceptingText )
inputMethodManager.hideSoftInputFromWindow( this.currentFocus.windowToken, /*flags:*/ 0)
}
Em seguida, consuma usando:
// from activity
this.dismissKeyboard()
// from fragment
activity.dismissKeyboard()
A primeira solução com o InputMethodManager funcionou como um campeão para mim, o método getWindow (). SetSoftInputMode não funcionou no Android 4.0.3 HTC Amaze.
@ Ethan Allen, não precisava finalizar a edição do texto. Talvez você esteja usando uma classe interna EditText que você declarou como método de contenção? Você pode tornar o EditText uma variável de classe da Atividade. Ou apenas declare um novo EditText dentro da classe / método interno e use findViewById () novamente. Além disso, não achei que precisava saber qual EditText no formulário tinha foco. Eu poderia escolher um arbitrariamente e usá-lo. Igual a:
EditText myEditText= (EditText) findViewById(R.id.anyEditTextInForm);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
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();
}
}
Esta solução garante que oculta o teclado e não faça nada se não estiver aberto. Ele usa extensão para poder ser usado em qualquer classe de Proprietário do Contexto.
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)
}
}
Usando o contexto da visualização, podemos obter o resultado desejado com os seguintes métodos de extensão no 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
)
Quando estes estiverem no lugar, basta ligar para:
editTextFoo.dismiss()