Activity中需要启动一个AlertDialog,这个对话框使用的是自定义布局,在这个对话框里有个EditText,可能是自定义布局的问题,导致对话框弹出时不能自动打开软键盘并定位焦点到文本框里。
dialog.show(); dialog.setContentView(windowLayout);
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);show之后设置红色代码AlertDialog里的Edittext可获得焦点
在dialog 里findViewById,拿到Edittext,requestFocus也不好使,因为dialog还没有完全展示到屏幕上,类似于Activity还没有执行OnResume。
解决方法:延迟一会儿调出输入法
可以在自定义的dialog中增加如下方法:
- public void showKeyboard() {
- if(editText!=null){
- //设置可获得焦点
- editText.setFocusable(true);
- editText.setFocusableInTouchMode(true);
- //请求获得焦点
- editText.requestFocus();
- //调用系统输入法
- InputMethodManager inputManager = (InputMethodManager) editText
- .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
- inputManager.showSoftInput(editText, 0);
- }
- }
在dialog.show()后,
- dialog.show();
- Timer timer = new Timer();
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
- dialog.showKeyboard();
- } }, 300);
网上查这样也可以,未测试
- dialog.setOnShowListener(newOnShowListener(){
- publicvoid onShow(DialogInterface dialog){
- InputMethodManager imm= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.showSoftInput(et_dialog_confirmphoneguardpswd,InputMethodManager.SHOW_IMPLICIT);
- }
- });