Android: affiche automatiquement le clavier logiciel lorsque le focus est sur un EditText

Je montre une zone de saisie en utilisant AlertDialog . Le EditText à l’intérieur de la boîte de dialog est automatiquement mis au point lorsque j’appelle AlertDialog.show() , mais le clavier EditText n’est pas affiché automatiquement.

Comment puis-je afficher automatiquement le clavier logiciel lorsque la boîte de dialog est affichée? (et il n’y a pas de clavier physique / matériel). De la même manière que lorsque j’appuie sur le bouton Rechercher pour appeler la recherche globale, le clavier logiciel s’affiche automatiquement.

Vous pouvez créer un programme d’écoute sur EditText sur AlertDialog , puis obtenir la Window AlertDialog . De là, vous pouvez faire apparaître le clavier setSoftInputMode appelant setSoftInputMode .

 final AlertDialog dialog = ...; editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }); 

Pour montrer l’utilisation du clavier:

 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); 

Pour masquer l’utilisation du clavier:

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

Vous pouvez demander un clavier logiciel juste après la création de la boîte de dialog (test sur le SDK – r20)

 // create dialog final AlertDialog dialog = ...; // request keyboard dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); 

J’ai eu le même problème et l’ai résolu avec le code suivant. Je ne sais pas comment cela se comportera sur un téléphone avec un clavier matériel.

 // TextEdit final EditText textEdit = new EditText(this); // Builder AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Enter text"); alert.setView(textEdit); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Ssortingng text = textEdit.getText().toSsortingng(); finish(); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); // Dialog AlertDialog dialog = alert.create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT); } }); dialog.show(); 

J’ai trouvé cet exemple http://android-codes-examples.blogspot.com/2011/11/show-or-hide-soft-keyboard-on-opening.html . Ajoutez le code suivant juste avant alert.show() .

 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); 
   

ou

 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); 

Les extraits de code provenant d’autres réponses fonctionnent, mais il n’est pas toujours évident de les placer dans le code, en particulier si vous utilisez un AlertDialog.Builder et AlertDialog.Builder le didacticiel car il n’utilise pas final AlertDialog ... ou alertDialog.show() .

 alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); 

Est préférable à

 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); 

Parce que SOFT_INPUT_STATE_ALWAYS_VISIBLE masquera le clavier si le focus s’éloigne de EditText, où SHOW_FORCED gardera le clavier affiché jusqu’à ce qu’il soit explicitement rejeté, même si l’utilisateur retourne à l’écran d’accueil ou affiche les applications récentes.

Vous trouverez ci-dessous un code de travail pour un AlertDialog créé à l’aide d’une disposition personnalisée avec un EditText défini en XML. Il définit également le clavier pour avoir une touche “go” et lui permet de déclencher le bouton positif.

alert_dialog.xml:

      

AlertDialog.java:

 import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatDialogFragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.EditText; public class CreateDialog extends AppCompatDialogFragment { // The public interface is used to send information back to the activity that called CreateDialog. public interface CreateDialogListener { void onCreateDialogCancel(DialogFragment dialog); void onCreateDialogOK(DialogFragment dialog); } CreateDialogListener mListener; // Check to make sure that the activity that called CreateDialog implements both listeners. public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (CreateDialogListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toSsortingng() + " must implement CreateDialogListener."); } } // onCreateDialog requires @NonNull. @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()); LayoutInflater customDialogInflater = getActivity().getLayoutInflater(); // Setup dialogBuilder. alertDialogBuilder.setTitle(R.ssortingng.title); alertDialogBuilder.setView(customDialogInflater.inflate(R.layout.alert_dialog, null)); alertDialogBuilder.setNegativeButton(R.ssortingng.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mListener.onCreateDialogCancel(CreateDialog.this); } }); alertDialogBuilder.setPositiveButton(R.ssortingng.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mListener.onCreateDialogOK(CreateDialog.this); } }); // Assign the resulting built dialog to an AlertDialog. final AlertDialog alertDialog = alertDialogBuilder.create(); // Show the keyboard when the dialog is displayed on the screen. alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); // We need to show alertDialog before we can setOnKeyListener below. alertDialog.show(); EditText editText = (EditText) alertDialog.findViewById(R.id.editText); // Allow the "enter" key on the keyboard to execute "OK". editText.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button, select the PositiveButton "OK". if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // Trigger the create listener. mListener.onCreateDialogOK(CreateDialog.this); // Manually dismiss alertDialog. alertDialog.dismiss(); // Consume the event. return true; } else { // If any other key was pressed, do not consume the event. return false; } } }); // onCreateDialog requires the return of an AlertDialog. return alertDialog; } } 

Jetez un coup d’œil à cette discussion qui permet de cacher et d’afficher manuellement l’IME. Cependant, mon sentiment est que si un EditText ciblé EditText pas l’IME, c’est parce que vous appelez AlertDialog.show() dans votre OnCreate() ou une autre méthode évoquée avant que l’écran ne soit réellement présenté. Le déplacer dans OnPostResume() devrait le réparer dans ce cas je crois.

Permettez-moi de signaler quelques informations supplémentaires à la solution de yuku, parce que j’ai eu du mal à le faire fonctionner! Comment puis-je obtenir l’object AlertDialog de mon AlertDialog.Builder? Eh bien, c’est le résultat de mon exécution alert.show() :

 final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); final EditText input = new EditText(getActivity()); alert.setView(input); // do what you need, like setting positive and negative buttons... final AlertDialog dialog = alert.show(); input.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }); 

Eh bien, c’est un vieux message, il y a encore quelque chose à append.
Ce sont deux méthodes simples qui me permettent de garder le clavier sous contrôle et qui fonctionnent parfaitement:

Afficher le clavier

 public void showKeyboard() { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); View v = getCurrentFocus(); if (v != null) imm.showSoftInput(v, 0); } 

Masquer le clavier

 public void hideKeyboard() { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); View v = getCurrentFocus(); if (v != null) imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } 

Oui, vous pouvez faire avec setOnFocusChangeListener cela vous aidera.

 editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }); 

Si quelqu’un obtient:

Impossible de faire une référence statique à la méthode non statique getSystemService (Ssortingng) à partir du type Activity

Essayez d’append un contexte à l’appel getSystemService.

Alors

 InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); 

La question originale concerne Dialogs et mon EditText est sur une vue régulière. Quoi qu’il en soit, je pense que cela devrait fonctionner pour la plupart d’entre vous. Donc, voici ce qui fonctionne pour moi (la méthode de notation la plus élevée suggérée ci-dessus n’a rien fait pour moi). Voici un EditView personnalisé qui le fait (le sous-classement n’est pas nécessaire, mais je l’ai trouvé pratique pour mes besoins, car je voulais également saisir le focus lorsque la vue devient visible).

C’est en fait largement la même chose que la réponse de tidbeck. Je n’ai en fait pas remarqué sa réponse car il y avait zéro vote. Ensuite, j’étais sur le sharepoint commenter son article, mais cela aurait été trop long, alors j’ai fini par faire ce post quand même. tidbeck fait remarquer qu’il ne sait pas comment cela fonctionne avec les appareils dotés de claviers. Je peux confirmer que le comportement semble être exactement le même dans les deux cas. Cela étant, sur le mode portrait, le clavier du logiciel apparaît et sur le paysage, ce n’est pas le cas. Avoir le clavier physique sorti ou ne fait aucune différence sur mon téléphone.

Parce que, personnellement, j’ai trouvé le comportement un peu maladroit que j’ai choisi d’utiliser: InputMethodManager.SHOW_FORCED . Cela fonctionne comme je le voulais. Le clavier devient visible, quelle que soit l’orientation. Cependant, au moins sur mon appareil, il n’apparaît pas si le clavier matériel a été glissé.

 import android.app.Service; import android.content.Context; import android.util.AtsortingbuteSet; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; public class BringOutTheSoftInputOnFocusEditTextView extends EditText { protected InputMethodManager inputMethodManager; public BringOutTheSoftInputOnFocusEditTextView(Context context, AtsortingbuteSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public BringOutTheSoftInputOnFocusEditTextView(Context context, AtsortingbuteSet attrs) { super(context, attrs); init(); } public BringOutTheSoftInputOnFocusEditTextView(Context context) { super(context); init(); } private void init() { this.inputMethodManager = (InputMethodManager)getContext().getSystemService(Service.INPUT_METHOD_SERVICE); this.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { BringOutTheSoftInputOnFocusEditTextView.this.inputMethodManager.showSoftInput(BringOutTheSoftInputOnFocusEditTextView.this, InputMethodManager.SHOW_FORCED); } } }); } @Override protected void onVisibilityChanged(View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (visibility == View.VISIBLE) { BringOutTheSoftInputOnFocusEditTextView.this.requestFocus(); } } } 

Le problème semble être que AlertDialog définit automatiquement l’indicateur WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM ou WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE pour que les choses ne déclenchent pas une entrée WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE . se montrer.

La façon de résoudre ce problème est d’append ce qui suit:

 (...) // Create the dialog and show it Dialog dialog = builder.create() dialog.show(); // After show (this is important specially if you have a list, a pager or other view that uses a adapter), clear the flags and set the soft input mode dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); 

essayez et utilisez:

 editText.requestFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); 

Pour montrer le clavier, pour moi, je devais faire ce qui suit

Android TextField: définir le focus + soft input par programmation

La solution est essentiellement la suivante

 @Override public void onResume() { super.onResume(); //passwordInput.requestFocus(); <-- that doesn't work passwordInput.postDelayed(new ShowKeyboard(), 325); //250 sometimes doesn't run if returning from LockScreen } 

ShowKeyboard est

 private class ShowKeyboard implements Runnable { @Override public void run() { passwordInput.setFocusableInTouchMode(true); //passwordInput.requestFocusFromTouch(); //this gives touch event to launcher in background -_- passwordInput.requestFocus(); getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(passwordInput, 0); } } 

Après une saisie réussie, je m'assure également de cacher le clavier

 getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(getView().getWindowToken(), 0); 

Ceci est un bon échantillon pour vous:

              

Pourquoi cette réponse – Parce que la solution ci-dessus affichera votre clavier mais ne disparaîtra pas si vous cliquez n’importe où ailleurs sur EditText . Vous devez donc faire quelque chose pour que le clavier disparaisse lorsque EditText perd le focus.

Vous pouvez y parvenir en procédant comme suit:

  1. Rendre la vue parent (vue du contenu de votre activité) cliquable et focalisable en ajoutant les atsortingbuts suivants

      android:clickable="true" android:focusableInTouchMode="true" 
  2. Implémenter une méthode hideKeyboard ()

      public void hideKeyboard(View view) { InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY ); } 
  3. Enfin, définissez onFocusChangeListener de votre edittext.

      edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { hideKeyboard(v); } } }); 

C’est un peu compliqué. J’ai fait de cette façon et cela a fonctionné.

1.Au premier appel pour masquer l’entrée logicielle de la fenêtre. Cela masquera l’entrée si le clavier logiciel est visible ou ne fait rien si ce n’est pas le cas.

2.Afficher votre dialog

3.Pas simplement appeler pour basculer l’entrée modérée.

code:

 InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); //hiding soft input inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWind‌​owToken(), 0); //show dialog yourDialog.show(); //toggle soft input inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT); 

Essaye ça

SomeUtils.java

 public static void showKeyboard(Activity activity, boolean show) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if(show) inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); else inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0); }