在我們寫修改信息或者搜索,修改密碼等界面的時候,用戶進入這個界面的主要目的就是輸入修改/查找 某些信息,為了用戶體驗應該自動彈出軟鍵盤而不是讓用戶主動點擊輸入框才彈出。
1.軟鍵盤的自動彈出
private void showKeyboard(){InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);inputMethodManager.showSoftInput(editText, 0);}
對于界面比較復雜的情況的時候,軟鍵盤可能無法正常的彈出,需要延遲加載。即在界面加載完成之后,彈出軟鍵盤
- 1.1 使用 定時器 schedule
Timer timer = new Timer();timer.schedule(new TimerTask() {public void run() { InputMethodManager inputManager = (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(editText, 0); } }, 998);
-
1.2 使用 handler
2.軟鍵盤的關閉
我遇到過一種情況是,首頁是scrollView 包裹的界面,滾動一段距離后進入下一個頁面,會彈出軟鍵盤,當關閉該界面的時候(即直接 finish()),回到首頁的時候,scrollView 不是原來的位置了。處理辦法就是 在有軟鍵盤彈出的頁面,先關閉軟鍵盤,再 finish()界面。
private void closeKeyboard() {View view = getWindow().peekDecorView();if (view != null) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } }
3.軟鍵盤把某些布局擠上去了的情況
<activityandroid:name=".activity.DetailActivity"android:screenOrientation="portrait"android:windowSoftInputMode="adjustPan"android:theme="@style/AppTheme.NoActionBar.Translucent"/>
主要就是 windowSoftInputMode 這個屬性,其中2個比較重要的是 adjustPan 和 adjustResize
adjustPan 不會把底部的布局給擠上去,例如relateLayout 布局中 放到bottom 的布局
adjustResize 是自適應的,會把底部的擠上去。
更詳細的可以了解下 windowSoftInputMode 這個屬性,好多大神的博客上都有說明,我這就不贅述了。