2013-08-07 34 views
1

我有一個屏幕,其中有一個警告框。如何在android中自動隱藏鍵盤?

在此警報框中有一個微調控件和兩個文本字段。

問題是當我選擇任何文本字段時,它會打開鍵盤,但當我單擊外部文本框時,我需要隱藏鍵盤,我已經使用下面給出的方法來隱藏鍵盤,但它不隱藏鍵盤,警報框。

@Override 
public boolean dispatchTouchEvent(MotionEvent event) { 
    // TODO Auto-generated method stub 
    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]; 

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

任何人都可以請告訴我爲什麼它只是創建警報框的問題。

請幫幫我。

+0

http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard?rq=1這應該解決您的問題。 – Manu

回答

0

試試這個代碼:

public void showSoftKeyboard() { 
    try { 
     InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); 
     inputMethodManager.toggleSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.SHOW_FORCED, 0); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public void hideSoftKeyboard() { 
    try { 
     InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); 
     inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 
+0

這不是自動的:-( –