2010-10-23 18 views
16

Quiero ocultar el teclado virtual cuando hago clic en el lado de editbox en una pantalla. ¿Cómo puedo hacer esto?ocultar teclado predeterminado al hacer clic en android

+0

Debería hacerlo automáticamente. Siempre que haga clic en algún lugar que no aparezca en el teclado – Falmarri

+0

@Falmarri Inicialmente pensé que tenía usted razón, pero no puedo hacer que esto suceda en mi aplicación de prueba. Escenario probado: 1) haga clic en una vista EditText que hace aparecer el teclado, 2) haga clic en una SeekBar en el mismo Fragment 3) haga clic en RadioButton con enfocable = verdadero. Ni 2 ni 3 cerraron el teclado. ¿Este comportamiento sugerido está documentado en alguna parte? – Nilzor

Respuesta

31

Para ocultar a la fuerza el teclado usaría el siguiente código ... Lo puse en un método llamado 'hideSoftKeyboard()'. Como menciona Falmarri, el teclado de la herramienta debería ocultarse al hacer clic en. Sin embargo, si llama a este método en un 'onClick()' de otro elemento, cerrará forzosamente el teclado.

private void hideSoftKeyboard(){ 
    if(getCurrentFocus()!=null && getCurrentFocus() instanceof EditText){ 
     InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
     imm.hideSoftInputFromWindow(yourEditTextHere.getWindowToken(), 0); 
    } 
} 
+0

No funciona desde 2015 – delive

6

He añadido lo siguiente a mi actividad. Funciona porque tocar fuera de una Vista enfocable no cambia el enfoque (por lo que w == v) pero el toque estará fuera del rectángulo de la Vista.

public boolean dispatchTouchEvent(MotionEvent event) { 
    View v = getCurrentFocus(); 
    boolean ret = super.dispatchTouchEvent(event); 
    View w = getCurrentFocus(); 
    int scrcoords[] = new int[2]; 
    w.getLocationOnScreen(scrcoords); 
    float x = event.getRawX() + w.getLeft() - scrcoords[0]; 
    float y = event.getRawY() + w.getTop() - scrcoords[1]; 

    Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]); 
    if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom())) { 
     inputManager.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0); 
    } 
    return ret; 

} 

[editar: corregir errores menores]

57

Tuvo que editar éste para conseguir que funcione. Se agregó una marca para ver si la vista enfocada es un EditarTexto.

@Override 
public boolean dispatchTouchEvent(MotionEvent event) { 

    View v = getCurrentFocus(); 
    boolean ret = super.dispatchTouchEvent(event); 

    if (v instanceof EditText) { 
     View w = getCurrentFocus(); 
     int scrcoords[] = new int[2]; 
     w.getLocationOnScreen(scrcoords); 
     float x = event.getRawX() + w.getLeft() - scrcoords[0]; 
     float y = event.getRawY() + w.getTop() - scrcoords[1]; 

     Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]); 
     if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom())) { 

      InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
      imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0); 
     } 
    } 
return ret; 
} 

Probablemente podría hacerse de una manera más suave, pero funciona muy bien.

+2

Para agregar un poco de aclaración: si está buscando cerrar el teclado cuando el usuario hace clic EN CUALQUIER FORO FUERA DE EDITTEXT, y no solo en otro botón onClick(), entonces el código de Daniel funciona perfectamente. Simplemente agregue/anule el método a su Actividad y el usuario podrá cerrar el teclado haciendo clic en cualquier lugar fuera de EditText (también funciona para varios EditTexts en una sola pantalla). Gracias Daniel! –

+2

Esta no es una respuesta perfecta ya que ocultará el teclado al tocar, no tocará. Si, por ejemplo, desplazarse un poco, el teclado estará oculto. Esto frecuentemente no es deseado. – Ixx

+0

@daniel gracias, este es el genio – bibangamba

6

Esto se puede hacer utilizando el código siguiente:

1) Tomar una referencia de su diseño matriz en código Java por medio de findViewById().

2) luego aplique setOnTouchListener() a él.

3) Agregue el siguiente código en onTouchMethod().

lin = (LinearLayout) findViewById(R.id.lin); 
    lin.setOnTouchListener(new OnTouchListener() 
    { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) 
     { 
       InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
           imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0); 
         return false; 
     } 
    }); 
0
public boolean OutsideTouchEvent(MotionEvent m_event) { 
    View v = getCurrentFocus(); 
    boolean value = super.dispatchTouchEvent(m_event); 
    View w = getCurrentFocus(); 
    int scrcoords[] = new int[2]; 
    w.getLocationOnScreen(scrcoords); 
    float x = m_event.getRawX() + w.getLeft() - scrcoords[0]; 
    float y = m_event.getRawY() + w.getTop() - scrcoords[1]; 

    if (m_event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom())) { 
     InputMethodManager inputMethodManager = (InputMethodManager) YourActivity.this.getSystemService(Activity.INPUT_METHOD_SERVICE); 
     inputMethodManager.hideSoftInputFromWindow(YourActivity.this.getCurrentFocus().getWindowToken(), 0); 
    } 
    return value; 

} 
0

conjunto inputType a cero para editar texto
editText.setInputType(0);

es un trabajo para mí

0

En primer lugar gracias a Daniel, su código es muy agradable y yo estaba usando por un momento.

Recientemente me di cuenta de que tengo que mejorarlo. El problema fue desplazar la página. Tenía muchos EditText s en mi proyecto y estaba ocultando el teclado cuando se desplazaba por la página.

me ocurrió una solución utilizando onGestureListener en lugar de anular dispatchTouchEvent.

public class TabActivity extends ActionBarActivity implements GestureDetector.OnGestureListener { 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ... 
     ... 
     gestureScanner = new GestureDetector(TabActivity.this,this); 
    } 

    @Override 
    public boolean dispatchTouchEvent(MotionEvent ev) { 
     gestureScanner.onTouchEvent(ev); 
     return super.dispatchTouchEvent(ev); 
    } 

    @Override 
    public boolean onSingleTapUp(MotionEvent event) { 
     View v = getCurrentFocus(); 

     if (v instanceof EditText) { 
      View w = getCurrentFocus(); 
      int scrcoords[] = new int[2]; 
      w.getLocationOnScreen(scrcoords); 
      boolean hide = true; 

      View view = ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0); 
      ArrayList<View> editTexts = view.getFocusables(0);  // Get All EditTexts in view 

      for(int i=0; i< editTexts.size(); i++){ 
       View editText = editTexts.get(i); 
       editText.getLocationOnScreen(scrcoords); 
       float x = event.getRawX(); 
       float y = event.getRawY(); 
       int viewX = scrcoords[0]; 
       int viewY = scrcoords[1]; 

       // If touch is in any of EditText, keep keyboard active, otherwise hide it. 
       if (event.getAction() == MotionEvent.ACTION_UP && (x > viewX && x < (viewX + editText.getWidth())) && (y > viewY && y < (viewY + editText.getHeight()))) { 
        hide = false; 
       } 
      } 

      if (hide) { 
       InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
       imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0); 
      } 
     } 
     return true; 
    } 

    @Override 
    public boolean onScroll(MotionEvent event, MotionEvent e2, float distanceX, float distanceY) { 
     return true; 
    }  
} 

lo tanto, si el usuario se desplaza por la página que va a onScroll método y no hace nada. Si los usuarios solo tocan en la pantalla, activa el método onSingleTapUp.

También tuve que cambiar si la declaración del código de Daniel. Daniel estaba comprobando si el evento táctil estaba fuera del EditText. Como tengo muchos EditViews, cambié el código para encontrar si el evento táctil se encuentra dentro de cualquiera de EditText s.

Funciona bien conmigo, avíseme para cualquier tipo de mejoras o errores.

+0

Ver view = ((ViewGroup) findViewById (android.R.id.content)). GetChildAt (0); no entendí esto ¿Podrías por favor explicarlo? – Tara

+0

Ese fue un viejo proyecto en el que trabajé, no recuerdo los detalles. Básicamente, lo que hago allí es recuperar la vista principal. 'android.R.id.content' le dará la vista raíz. 'getChildAt (0)' probablemente se use para recuperar el padre de mis EditTexts. –

+0

, ¿quiere decir agregar todo el texto de edición en el grupo de vista o dentro de la vista? – Tara

0

acaba de establecer el tipo de entrada a null como que

editText.setInputType(InputType.TYPE_NULL);

0

Como un complemento de la respuesta aceptada.

Si la respuesta aceptada no está trabajando para usted, usted puede añadir el método hideSoftKeyboard() con el método de la onClickListener de su EditTextonClick(). Por ejemplo:

editText.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     hideSoftKeyboard(); 
    } 
}); 

(coloque el código anterior en onResume() o en otro lugar)

ps. la definición de hideSoftKeyboard()

private void hideSoftKeyboard(){ 
    if(getCurrentFocus()!=null && getCurrentFocus() instanceof EditText){ 
     InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
     imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); 
    } 
} 
0

me dieron buenas solution.I saben de que sea demasiado tarde, pero cuando se busca la mayor parte de veces conseguir este enlace como primer enlace. por lo que puede ser útil para otros. Si hace clic en cualquier botón/texto, ocultará el teclado virtual que ya está visible.

date.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // Hide soft keyboard 
     InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); 
      imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); 

     // here i am showing the Date Dialog. one can proceed with their functionality 

      //show date picker dialog 
      showDialog(Date_DIALOG_ID); 
     } 
    }); 
Cuestiones relacionadas