网上好多方法说的隐藏方法,其实是隐藏/显示方法,即,当前键盘显示,调用一下,隐藏,在调用一下,又显示了。下面提供两种彻底隐藏的方法:
/**
* 软键盘显示/隐藏
*/
public void hideShowKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); //得到InputMethodManager的实例
if (imm.isActive()) {//如果开启
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);//关闭软键盘,开启方法相同,这个方法是切换开启与关闭状态的
}
}
/**
* 隐藏软键盘(只适用于Activity,不适用于Fragment)
*/
public void hideSoftKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* 隐藏软键盘(可用于Activity,Fragment)
*/
public void hideSoftKeyboard(Context context, List<View> viewList) {
if (viewList == null) return;
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
for (View v : viewList) {
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
其中viewList 中需要放的是当前界面所有触发软键盘弹出的控件。 比如一个登陆界面, 有一个账号输入框和一个密码输入框, 需要隐藏键盘的时候, 就将两个输入框对象放在 viewList 中, 作为参数传到 hideSoftKeyboard 方法中即可。
如何设置EditText默认不弹出软键盘,网上好多人说,editText.clearFoucs();然而我试了,并没卵用。
简单有效的办法是在EditText的父布局中添加两个focusable和focusableInTouchMode为true属性,如下:
<RelativeLayout
android:layout_width="480px"
android:layout_height="65px"
android:focusable="true"
android:focusableInTouchMode="true">
<EditText
android:id="@+id/et_local_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:hint="请输入视频名称"
android:textCursorDrawable="@null"
android:textSize="23px" />
</RelativeLayout>