2012-01-10 16 views
9

Ho un EditText nel mio Activity. Non appena viene avviato Activity, forzare l'apertura della tastiera virtuale mediante.Android: in che modo forzare la chiusura della tastiera virtuale quando è stata forzata l'apertura?

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
if (imm != null) { 
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); 
} 

Ora se la tastiera virtuale è aperta e si preme il pulsante Home, rimane aperta. Come posso forzarlo a chiudere sulla stampa di casa?

+0

vedere questo collegamento http://stackoverflow.com/questions/7200281/programatically-hide-show-android-soft-keyboard –

risposta

20
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
mgr.hideSoftInputFromWindow(Your Button.getWindowToken(), 0); 
1
@Override 
public boolean dispatchTouchEvent(MotionEvent event) { 
    View view = getCurrentFocus(); 
    boolean ret = super.dispatchTouchEvent(event); 

    if (view 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; 
} 

Questo codice chiude la tastiera quando si tocca un punto qualsiasi dello schermo.

+0

@ rashmi La soluzione suggerita è chiudere la tastiera virtuale quando viene chiamata implicitamente. qui lo sto forzando ad aprire quando la mia attività apre imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, 0); Quindi, questa soluzione non funziona – Vibhuti

Problemi correlati