Pergunta

eu tenho um Activity com um EditText, um botão e um ListView. O objetivo é digitar uma tela de pesquisa no EditText, pressione o botão e peça aos resultados da pesquisa preencher esta lista.

Tudo isso está funcionando perfeitamente, mas o teclado virtual está se comportando estranho.

Se eu clicar no EditText, Eu recebo o teclado virtual. Se eu clicar no botão "feito" no teclado virtual, ele desaparecerá. No entanto, se eu clicar no botão de pesquisa antes de clicar em "Concluído" no teclado virtual, o teclado virtual permanece e não consigo me livrar dele. Clicar no botão "feito" não fecha o teclado. Ele altera o botão "feito" de "Done" para uma seta e permanece visível.

Obrigado pela ajuda

Foi útil?

Solução 2

mMyTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // hide virtual keyboard
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(m_txtSearchText.getWindowToken(), 
                                      InputMethodManager.RESULT_UNCHANGED_SHOWN);
            return true;
        }
        return false;
    }
});

Outras dicas

InputMethodManager inputManager = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE); 

inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                     InputMethodManager.HIDE_NOT_ALWAYS);

Eu coloquei isso logo após o onClick(View v) evento.

Você precisa importar android.view.inputmethod.InputMethodManager;

O teclado se esconde quando você clica no botão.

Use o código abaixo

your_button_id.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try  {
            InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {

        }
    }
});

Você deve implementar OnEditorActionListener para o seu editview

public void performClickOnDone(EditView editView, final View button){
    textView.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(EditView v, int actionId, KeyEvent event) {
            hideKeyboard();
            button.requestFocus();
            button.performClick();
            return true;
        }
    });

E você esconde o teclado por:

public void hideKeybord(View view) {
    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),
                                  InputMethodManager.RESULT_UNCHANGED_SHOWN);
}

Você também deve disparar o teclado escondido no seu botão usando onClickListener

Agora, clicando em 'Concluído' no teclado virtual e no botão fará o mesmo - oculte o teclado e execute a ação de clique.

Adicione o seguinte código dentro do seu botão Clique em Evento:

InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

Como você tem apenas um texto de edição, basta ligar para a ação realizada para editar o texto dentro do botão Clique e o restante é tratado pelo sistema. Se você tivesse mais de um EditText, isso não seria tão eficaz porque você precisa obter o EditText focado primeiro. Mas, no seu caso, funcionará perfeitamente

myedittext.onEditorAction(EditorInfo.IME_ACTION_DONE)

Para atividade,

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

Para fragmentos, use getActivity ()

getActivity (). getSystemService ();

getActivity (). getCurrentFocus ();

InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);

Esta solução funciona perfeitamente para mim:

private void showKeyboard(EditText editText) {
    editText.requestFocus();
    editText.setFocusableInTouchMode(true);
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(editText, InputMethodManager.RESULT_UNCHANGED_SHOWN);
    editText.setSelection(editText.getText().length());
}

private void closeKeyboard() {
    InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
}

Experimente isso ...

  1. Para mostrar o teclado

    editText.requestFocus();
    InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    
  2. Para ocultar teclado

    InputMethodManager inputManager = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE); 
    inputManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);enter code here}

Você usa este código no seu evento de clique em botão

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

CRASH DO PONTO NULL Correção da exceção: eu tinha um caso em que o teclado pode não abrir quando o usuário clica no botão. Você precisa escrever uma instrução IF para verificar se GetCurrentFocus () não é um NULL:

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

Exemplo de Kotlin:

val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

De fragmento:

inputMethodManager.hideSoftInputFromWindow(activity?.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)

da atividade:

inputMethodManager.hideSoftInputFromWindow(currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)

Se você definir android:singleLine="true", automaticamente o botão esconde o teclado ^

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top