android自动弹出软键盘(输入键盘)

很多应用中对于一个界面比如进入搜索界面或者修改信息等等情况,为了用户体验应该自动弹出软键盘而不是让用户主动点击输入框才弹出(因为用户进入该界面必然是为了更改信息)。具体实现这种效果如下:

EditText  editText.setFocusable(true);  
editText.setFocusableInTouchMode(true);  
editText.requestFocus();  
MethodManager inputManager = (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);  
inputManager.showSoftInput(editText, 0); 

首先要对指定的输入框请求焦点。然后调用输入管理器弹出软键盘。

特别的:对于刚跳到一个新的界面就要弹出软键盘的情况,上述代码可能由于界面未加载完全而无法弹出软键盘。此时应该适当的延迟弹出软键盘,如200毫秒(保证界面的数据加载完成)。实例代码如下:

edtPay.setFocusableInTouchMode(true);
edtPay.requestFocus();
Timer timer = new Timer();
timer.schedule(new TimerTask()
               {
                   public void run()
                   {
                       InputMethodManager inputManager = (InputMethodManager)edtPay.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                       inputManager.showSoftInput(edtPay, 0);
                   }
               },
        200);
posted @ 2021-12-23 21:36  汉学  阅读(965)  评论(0)    收藏  举报