首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 隱藏軟鍵盤:正確使用 InputMethodManager

     編輯:程式設計綜合問答

問題現象

在 onCreate 中呼叫 imm.hideSoftInputFromWindow() 但軟鍵盤未隱藏。

原因分析

  • View 未附加到視窗:onCreate 時 View 尚未佈局完成,getWindowToken() 回傳 null
  • EditText 未取得焦點:隱藏軟鍵盤需針對**目前擁有焦點的 View**
  • 軟鍵盤模式設定:Manifest windowSoftInputMode 可能強制顯示

正確時機與方法

方案一:在 onResume/onWindowFocusChanged 中隱藏


@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);
    }
}

方案二:Manifest 設定預不顯示 (最簡單)


  

方案三:EditText XML 設定不自動聚焦


  



    

方案四:程式碼強制移除焦點


@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"
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved