2012-03-21 19 views
7

Estoy usando AlertDialog.Builder en Android para solicitar rápidamente al usuario el texto. El cuadro de diálogo aparece y funciona muy bien, pero el usuario debe hacer clic en el campo Editar texto para cargar el teclado virtual. ¿Hay alguna forma de abrir el teclado y enfocarlo cada vez que se abre mi cuadro de diálogo? Aquí está mi código:Enfoque y teclado predeterminados para editar texto en Android AlertDialog

final Map<String,Object> rowData = itemList.get(mPosition); 
        final EditText input = new EditText(searchList.getContext()); 
       input.requestFocus(); 


       input.setSingleLine(); 
       final AlertDialog dialog = new AlertDialog.Builder(searchList.getContext()) 
       .setTitle(StringUtils.getSafeString(rowData.get("label"))) 
       .setView(input) 
       .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         rowData.put("value", StringUtils.getSafeString(input.getText())); 
         searchList.invalidateViews(); 

        } 
       }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         // Do nothing. 
        } 
       }).create(); 
       dialog.show(); 

Respuesta

12

Utilice el siguiente código. Funcionó para mí

editText.setOnFocusChangeListener(new OnFocusChangeListener() { 
     @Override 
     public void onFocusChange(View v, boolean hasFocus) { 
      editText.post(new Runnable() { 
       @Override 
       public void run() { 
        InputMethodManager inputMethodManager= (InputMethodManager) YourActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE); 
        inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT); 
       } 
      }); 
     } 
    }); 
    editText.requestFocus(); 
+0

Muchas gracias, ¡esto funciona perfectamente! –

-2

en su diseño XML

llamada

<requestFocus/> 

dentro de su defecto EditarTexto

<EditText 
android:blabla 
.... 
<requestFocus/> 
/> 
+1

El AlertDialog.Builder no utiliza un diseño de XML, sólo se necesita en un EditarTexto que se creó en el código.Intenté llamar atención de solicitud en EditText generado en varios lugares, y no parece funcionar de la manera que me gustaría. Esta no es una solución funcional para esta pregunta. – cain

0

InputMethodManager imm = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, 0); Para ocultar el uso del teclado:

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

o intenta a continuación código, sino que debe establecer el requestFocus() oa su EditarTexto

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

teclado oculto al establecer mediante programación foco en un EditarTexto en un diálogo Android.

Tuve este problema también y fue una solución bastante simple: esta es mi solución sugerida. A pesar de que funcionó en DialogFragments para mí, no veo ninguna razón por la cual no funcionaría en su caso.

Básicamente, el teclado virtual no se activa porque la vista se está creando mediante programación. La solución real fue simplemente poner esta línea en el método onCreateDialog:

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

De la documentación de Android en DialogFragments:

Si el usuario se centra en un EditarTexto, el teclado en pantalla aparecerá automáticamente . Para forzar esto a que suceda con nuestro enfoque programático , llamamos a getDialog(). GetWindow(). SetSoftInputMode(). Tenga en cuenta que muchas de las operaciones de ventana que pudo haber hecho previamente en un cuadro de diálogo pueden seguir siendo realizadas en un cuadro de diálogo, pero debe llamar a getDialog(). GetWindow() en lugar de solo getWindow().

@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 

    //setup your dialog builder and inflate the view you want here 
    ... 
    //Make sure your EditText has the focus when the dialog is displayed 
    edit.requestFocus(); 
    //Create the dialog and save to a variable, so we can set the keyboard state 
    Dialog dialog = builder.create(); 
    //now, set to show the keyboard automatically 
    dialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE); 
    return dialog; 
} 
+1

¡Así se hace! Esta debería ser la respuesta aceptada. Usé 'getWindow(). SetSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);' en el constructor de mi subclase AppCompatDialog. –

+0

dialog.getWindow() puede devolver nulo –

0

usar una vista personalizada si lo necesita más a menudo

public class RequestFocusEditText extends AppCompatEditText { 
    private RequestFocusEditText self; 

    public RequestFocusEditText(final Context context, AttributeSet attrs) { 
     super(context, attrs); 
     this.self = this; 

     setOnFocusChangeListener(new OnFocusChangeListener() { 
      @Override 
      public void onFocusChange(View v, boolean hasFocus) { 
       post(new Runnable() { 
        @Override 
        public void run() { 
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 
        inputMethodManager.showSoftInput(self, InputMethodManager.SHOW_IMPLICIT); 
       } 
      }); 
     } 
    }); 
    requestFocus(); 
    } 
} 
Cuestiones relacionadas