2012-12-05 72 views
2

我已经尝试过几种方法,通过在onCreateOptionsMenu (Menu menu)中插入代码而没有成功。当我点击菜单按钮时,我想隐藏键盘。如何在点击菜单时隐藏默认键盘?

我有三个EditText,其中我写了一些数据,并且插入/删除/修改数据库的选项都在菜单上,但是如果我单击,键盘不会自动隐藏。

我有这样的事情:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 

    if(this.getCurrentFocus() != null && this.getCurrentFocus() instanceof EditText){ 
     InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
     imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
    } 
    return true; 
} 

它只适用于我第一次按下菜单按钮。

谢谢!

回答

0

移动代码onOptionsItemSelected代替

public boolean onOptionsItemSelected(MenuItem item) { 
    ..... 
    if(this.getCurrentFocus() != null && this.getCurrentFocus() instanceof EditText){ 
     InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
     imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
    } 
    return super.onOptionsItemSelected(item); 
} 
0

另一个地方,你可以把InputMethodManager代码是在onPrepareOptionsMenu()回调是这样的:

public boolean onPrepareOptionsMenu (Menu menu) { 
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
    return true; 
} 

,如果你想隐藏的键盘,您可能会更喜欢这个而不管用户是否实际上随后点击了任何菜单项目。

相关问题