2012-01-10 117 views
9

我有一个EditText在我的Activity。只要Activity开始,我强制软键盘打开使用。Android:如何强制打开软键盘时强制关闭软键盘?

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

现在,如果软键盘已打开,并且按Home键,它仍保持打开状态。我如何在家庭媒体上强制关闭它?

+0

请参阅此链接http://stackoverflow.com/questions/7200281/programatically-hide-show-android-soft-keyboard – 2012-01-10 09:26:06

回答

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

此代码关闭时你在任何地方触摸屏幕上的键盘。

+0

@ rashmi您建议的解决方案是在隐式调用软键盘时关闭软键盘。这里我强制它打开时,我的活动打开imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); 所以,此解决方案不起作用 – Vibhuti 2012-01-12 07:21:41