web-dev-qa-db-fra.com

Masquer le clavier en appuyant sur la touche retour

J'ai cherché une demi-douzaine d'autres réponses sur SO, mais je n'en ai trouvé aucune qui fonctionne. Tout ce que j'essaie de faire, c'est de fermer le clavier virtuel lorsque l'utilisateur appuie sur le bouton Entrée. (L'équivalent de l'appel insanement facile 'resignKeyboard' sur iOS.) Dans le code suivant, la méthode onEditorAction n'est pas appelée. J'ai configuré une vue EditText dans mon fichier XML et le code de mon fragment est le suivant:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        fragView = inflater.inflate(R.layout.fragment_encrypt2, container, false);
        textField = (EditText) fragView.findViewById(R.id.textField);

        textField.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView arg0, int actionId,
                                          KeyEvent arg2) {
                // hide the keyboard and search the web when the enter key
                // button is pressed
                if (actionId == EditorInfo.IME_ACTION_GO
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || actionId == EditorInfo.IME_ACTION_NEXT
                        || actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_SEARCH
                        || (arg2.getAction() == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(textField.getWindowToken(), 0);

                    return true;
                }
                return false;
            }
        });

        // Inflate the layout for this fragment
        return fragView;//inflater.inflate(R.layout.fragment_encrypt2, container, false);
    }

Ce qui suit est un extrait du fichier XML dans lequel je définis le champ EditText. J'ai besoin d'EditText pour être multiligne.

<EditText
            Android:id="@+id/textField"
            Android:layout_width="match_parent"
            Android:layout_height="match_parent"
            Android:hint="@string/Encrypted_Text_Hint"
            Android:gravity="top"
            Android:inputType="textMultiLine"
            Android:imeOptions="actionDone"/>
28
cph2117

Si vous ne voulez pas plusieurs lignes, pour vous edittext, vous pouvez simplement spécifier une seule ligne pour edittext et vous pouvez aussi mettre imeOptions comme Fait comme ceci

<EditText 
   Android:id="@+id/edittext_done"
   Android:layout_width="fill_parent"
   Android:layout_height="wrap_content"
   Android:imeOptions="actionDone"
   Android:singleLine="true"
   />

Je ne sais clairement pas si vous essayez d'atteindre cet objectif ou non.

EDIT: Android: singleLine est obsolète depuis l'API 3 en raison de mauvaises performances, vous devez utiliser Android: maxLines à la place. singleLine sera disponible, car certains effets ne sont pas encore pris en charge par Android: attribut maxLines.

59
George Thomas

J'ai résolu le problème en modifiant les éléments suivants dans le fichier XML à partir de:

 Android:inputType="textMultiLine"

à:

 Android:inputType="textImeMultiLine"
10
cph2117

Le code ci-dessous fonctionne pour moi.

EN XML:

    Android:imeOptions="actionDone"
    Android:inputType="textCapWords"

EN CLASSE Java:

    edit_text.setOnEditorActionListener(new OnEditorActionListener() {

                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    // TODO Auto-generated method stub

                    if ((actionId==EditorInfo.IME_ACTION_DONE )   )
                     {   
                        //Toast.makeText(getActivity(), "call",45).show();
                       // hide virtual keyboard
                       InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

                       //or try following:
                       //InputMethodManager imm = (InputMethodManager)getBaseContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                       imm.hideSoftInputFromWindow(auto_data.getWindowToken(), 0);
                       return true;
                    }
                    return false;

                }
            });
8
Ketan Patel

Sur la base de mes tests, ce qui est vraiment nécessaire pour ignorer le clavier logiciel, lorsqu'un utilisateur clique sur le bouton Entrée, peut être obtenu simplement en ajoutant le code ci-dessous à votre EditText au format XML. 

Android:imeOptions="actionDone"
Android:inputType="textImeMultiLine"

Pas besoin de OnEditorActionListener ou de tout autre code Java.

3
Chizoba Ogbonna

La réponse acceptée est déconseillée:

<EditText 
   Android:id="@+id/edittext_done"
   Android:layout_width="fill_parent"
   Android:layout_height="wrap_content"
   Android:imeOptions="actionDone"
   Android:singleLine="true"
/>

Essayez avec ceci:

<EditText 
   Android:id="@+id/edittext_done"
   Android:layout_width="fill_parent"
   Android:layout_height="wrap_content"
   Android:imeOptions="actionDone"
   Android:maxLines="1"
/>
3
Jorge Chavez

EditText.xml

<EditText
        Android:id="@+id/edit_text_searh_home"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:padding="4dp"
        Android:singleLine="true"
        Android:lines="1"
        Android:hint="Ingresa palabras claves"
        Android:imeActionLabel="Search"
        Android:background="@drawable/rounded_edit_text_search"
        Android:drawableRight="@Android:drawable/ic_menu_search"/>

Fragment.Java

final EditText edit_text_searh = (EditText) v.findViewById(R.id.edit_text_searh_home);

    edit_text_searh.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(edit_text_searh.getWindowToken(), 0);

            Toast.makeText(getContext(),edit_text_searh.getText(),Toast.LENGTH_SHORT).show();
            return true;

        }
    });

Essayez cette méthode, cela pourrait résoudre votre problème.

protected void showKeyboard() {

            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (activity.getCurrentFocus() == null) {
                inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
            } else {
                View view = activity.getCurrentFocus();
                inputMethodManager.showSoftInput(view,InputMethodManager.SHOW_FORCED);
            }
        }

        /**
         * Hide keyboard.
         */
        protected void hideKeyboard() {

            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            View view = activity.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);
            }          
        }
0
samsad

Cela peut être que vous pourriez ajouter un attribut à votre EditText comme ceci:

Android:imeOptions="actionSearch"
0
VVB