EditText获取不到焦点以及不自动弹出软键盘

按照广大热心网友的指导,做了以下操作:

ditText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

以及在AndroidManifest.xml中设置:

android:windowSoftInputMode="stateVisible|adjustResize"

然鹅,发现并无卵用。后来看到个觉得靠谱的解释:

Android加载刷新UI的时候,是从左到右,从上到下的顺序,正在加载的过程中,如果此时requestFocus(),的话,有可能此时还没把整个界面刷新好,导致requestFocus无效。

因此,做了个延迟加载:

editText.postDelayed(() -> {
           editText.setFocusable(true);
           editText.setFocusableInTouchMode(true);
           editText.requestFocus();
       }, 300);

果然就可以了,看到光标开始在闪了,可是此时如果想让他自动弹出来呢?
直接贴上完整代码吧,延时时间自定:

   /**
    * EditText获取焦点并显示软键盘
    */
   public static void showSoftInputFromWindow(Activity activity, EditText editText) {
    
       editText.postDelayed(() -> {
           editText.setFocusable(true);
           editText.setFocusableInTouchMode(true);
           editText.requestFocus();
           editText.setSelection(editText.getText().toString().length()); //移动光标到最后
       }, 300);
       // 强制打开键盘
       Timer timer = new Timer();
       timer.schedule(new TimerTask() {
           @Override
           public void run() {
               InputMethodManager inputMethodManager =
                       (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
               inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
           }
       }, 200);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值