Android隐藏软键盘

Bertha 。 2022-05-13 07:50 444阅读 0赞

网上好多方法说的隐藏方法,其实是隐藏/显示方法,即,当前键盘显示,调用一下,隐藏,在调用一下,又显示了。下面提供两种彻底隐藏的方法:

  1. /**
  2. * 软键盘显示/隐藏
  3. */
  4. public void hideShowKeyboard() {
  5. InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); //得到InputMethodManager的实例
  6. if (imm.isActive()) {//如果开启
  7. imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);//关闭软键盘,开启方法相同,这个方法是切换开启与关闭状态的
  8. }
  9. }
  10. /**
  11. * 隐藏软键盘(只适用于Activity,不适用于Fragment)
  12. */
  13. public void hideSoftKeyboard(Activity activity) {
  14. View view = activity.getCurrentFocus();
  15. if (view != null) {
  16. InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
  17. inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
  18. }
  19. }
  20. /**
  21. * 隐藏软键盘(可用于Activity,Fragment)
  22. */
  23. public void hideSoftKeyboard(Context context, List<View> viewList) {
  24. if (viewList == null) return;
  25. InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
  26. for (View v : viewList) {
  27. inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
  28. }
  29. }

其中viewList 中需要放的是当前界面所有触发软键盘弹出的控件。 比如一个登陆界面, 有一个账号输入框和一个密码输入框, 需要隐藏键盘的时候, 就将两个输入框对象放在 viewList 中, 作为参数传到 hideSoftKeyboard 方法中即可。


如何设置EditText默认不弹出软键盘,网上好多人说,editText.clearFoucs();然而我试了,并没卵用。

简单有效的办法是在EditText的父布局中添加两个focusable和focusableInTouchMode为true属性,如下:

  1. <RelativeLayout
  2. android:layout_width="480px"
  3. android:layout_height="65px"
  4. android:focusable="true"
  5. android:focusableInTouchMode="true">
  6. <EditText
  7. android:id="@+id/et_local_search"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:background="@null"
  11. android:hint="请输入视频名称"
  12. android:textCursorDrawable="@null"
  13. android:textSize="23px" />
  14. </RelativeLayout>

发表评论

表情:
评论列表 (有 0 条评论,444人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android隐藏键盘

    网上好多方法说的隐藏方法,其实是隐藏/显示方法,即,当前键盘显示,调用一下,隐藏,在调用一下,又显示了。下面提供两种彻底隐藏的方法: / 软键盘显