第一种:弹出时判断是哪个控件下,收起时判断焦点
protected void hideSoftKeyboard()
{
if (getActivity().getCurrentFocus() != null)
{
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
}
protected void showSoftKeyboard(View v){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
v.setFocusable(true);
v.requestFocus();
if(getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
{
imm.showSoftInput(v , InputMethodManager.SHOW_FORCED);
}
}
第二种:和第一种相反
protected void hideSoftKeyboard(View v)
{
InputMethodManager imm = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm!=null){
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
protected void showSoftKeyboard()
{
if (getActivity().getCurrentFocus() != null)
{
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(getActivity().getCurrentFocus(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
推荐第一种用法。需要注意的是,如果Activity或Fragment的View没有初始化完毕,想要用以上方法默认自动弹出软键盘有可能会失败,此时需要提供一个延时弹出或者定时弹出,给几百毫秒左右,等Activity或Fragment的视图初始化完毕后再调用上面的方法。
Handler handler = new Handler();
private void initSoftInput(){
Runnable runnable = new Runnable() {
@Override
public void run() {
showSoftKeyboard(et_test); //弹出软键盘,et_test为输入框View
}
};
handler.postDelayed(runnable,300);
}