Android弹出式对话框AlertDialog中的EditText自动打开软键盘

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中增加如下方法:
  1. public void showKeyboard() {  
  2.         if(editText!=null){  
  3.             //设置可获得焦点  
  4.             editText.setFocusable(true);  
  5.             editText.setFocusableInTouchMode(true);  
  6.             //请求获得焦点  
  7.             editText.requestFocus();  
  8.             //调用系统输入法  
  9.             InputMethodManager inputManager = (InputMethodManager) editText  
  10.                     .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);  
  11.             inputManager.showSoftInput(editText, 0);  
  12.         }  
  13.     }  
editText为自定义dialog中的输入框的view
在dialog.show()后,
  1. dialog.show();  
  2. Timer timer = new Timer();  
  3. timer.schedule(new TimerTask() {  
  4.   
  5.     @Override  
  6.     public void run() {  
  7.         dialog.showKeyboard();  
  8.     }  }, 300);  



网上查这样也可以,未测试

  1. dialog.setOnShowListener(newOnShowListener(){
  2. publicvoid onShow(DialogInterface dialog){
  3. InputMethodManager imm= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
  4. imm.showSoftInput(et_dialog_confirmphoneguardpswd,InputMethodManager.SHOW_IMPLICIT);
  5. }
  6. });



你可能感兴趣的:(android)