【Android】AlertDialog中的EditText不能弹出软键盘的问题
2017-01-20 10:44
453 查看
摘要
AlertDialog中加入EditText但是不弹出软键盘等问题网上有很多不管用的解决方案,有的方案是强制弹出软键盘,然而即使弹出来,也是显示在AlertDialog的后面,被Dialog遮挡。解决方案
Dialog的官方文档:http://developer.android.com/reference/android/app/Dialog.html ,其中有一段:Note: Activities provide a facility to manage the creation, saving and restoring of dialogs. See onCreateDialog(int), onPrepareDialog(int, Dialog), showDialog(int), and dismissDialog(int). If these methods are used, getOwnerActivity() will return the Activity that managed this dialog.
Often you will want to have a Dialog display on top of the current input method, because there is no reason for it to accept text. You can do this by setting the WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM window flag (assuming your Dialog takes input focus, as it the default) with the following code:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
这段话的大概意思是说,WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM 这个参数会让Dialog遮挡住软键盘,显示在软键盘的前面。
这是默认情况下隐藏软键盘的方法,要重新显示软键盘,要执行下面这段代码:
alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
我是把它写在了setOnFocusChangeListener里,起效了
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean focused) { if (focused) { //dialog弹出软键盘 alertDialog.getWindow() .clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); } } });
AlertDialog.setView()则不会出现以上问题。
另外
为了防止弹出输入法时把后面的背景挤变形,可以在Manifest里的相应Activity添加:android:windowSoftInputMode="adjustPan|stateHidden"
像这样:
<activity android:name=".MainActivity" android:windowSoftInputMode="adjustPan|stateHidden" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
【参考资料】
1、关于AlertDialog中EditText不能弹出输入法解决方法相关文章推荐
- Android基础—Handler消息机制
- Android 调用webService+回调接口+线程池工具类封装(支持json格式接口和xml格式接口)
- 图片的转换
- android 7.0 Settings列表加载流程
- Android 测试教程
- android selector 备忘
- android 手机屏幕密度等级和屏幕逻辑尺寸
- 关于Android点击物理返回键退出程序的问题
- Mac Android Studio将项目(library)上传到jcenter
- Android基础—AsyncTask机制
- Android使用selector修改按钮正常和按下状态的颜色和形状
- Android生命周期
- 第八天 Android学习总结(服务)
- 文章标题
- Android实现控件拖动的小Demo
- Android利用Collections工具类处理集合对象
- Android 自定义通用的loadingview
- 设置输入法弹出时不占满整个屏幕
- Android 延时执行任务的三种简单方法
- Android 图片圆角的简单方法