在 onCreate 中呼叫 imm.hideSoftInputFromWindow() 但軟鍵盤未隱藏。
onCreate 時 View 尚未佈局完成,getWindowToken() 回傳 nullwindowSoftInputMode 可能強制顯示
@Override
public void onResume() {
super.onResume();
hideKeyboard();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) hideKeyboard();
}
private void hideKeyboard() {
View view = this.getCurrentFocus(); // 取得目前焦點 View
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找一個可聚焦的非 EditText View (如根佈局) 要求焦點
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setFocusableInTouchMode(true);
rootView.requestFocus();
// 或直接隱藏
new Handler().postDelayed(this::hideKeyboard, 100); // 延遲確保 View 就緒
}
public class KeyboardUtils {
public static void showKeyboard(Activity activity, EditText editText) {
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
public static void hideKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
if (view == null) view = new View(activity); // 防空指標
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public static void toggleKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
| 情況 | 結果 | 解決 |
|---|---|---|
| onCreate 呼叫 hide | 無效 (View 未就緒) | 用 onResume、onWindowFocusChanged 或 Handler 延遲 |
| DialogFragment 中隱藏 | 需用 dialog.getWindow() | imm.hideSoftInputFromWindow(dialog.getWindow().getDecorView().getWindowToken(), 0) |
| 全螢幕模式 | 軟鍵盤可能遮擋內容 | Manifest android:windowSoftInputMode="adjustResize" |