Android-UI-AlertDialog弹出关闭软键盘问题

2019-04-22  本文已影响0人  UU5209966

参考资料

http://toughcoder.net/blog/2015/10/09/android-trick-detect-soft-keyboard-show-slash-hide/

https://blog.csdn.net/lzw136296634/article/details/73549220

1.在AlertDialog.show()后设置可弹出键盘

AlertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

2.监听dismiss事件,隐藏软键盘

//AlertDialog 的onTouchOutSide设置为 true,通过dismiss关闭已打开的软键盘

AlertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

@Override public void onDismiss(DialogInterface dialogInterface) {

  //隐藏软键盘

    if(activity != null)

    if (isKeyboardShow(activity)){

            InputMethodManager imm = (InputMethodManager)                          activity.getSystemService(Context.INPUT_METHOD_SERVICE);

            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); }

    }

});

//判断键盘是否弹出

private static boolean isKeyboardShow(Activity activity) {

     View rootView = activity.getWindow().getDecorView().findViewById(android.R.id.content); 

     final int softKeyboardHeight = 100; Rect r = new Rect();

    rootView.getWindowVisibleDisplayFrame(r);

    DisplayMetrics dm = rootView.getResources().getDisplayMetrics(); 

     int heightDiff = rootView.getBottom() - r.bottom;

     return heightDiff > softKeyboardHeight * dm.density;

 }

上一篇下一篇

猜你喜欢

热点阅读