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.     }  
在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. });



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值