7

構造を美しく見せるために、アクティビティまたはフラグメントから getCurrentFocus() を呼び出したいのですが、どのようにメソッドを呼び出すことができますか? 同様の機能を実現するために、コンテキストをパラメーターとして使用することがあります。

4

2 に答える 2

26

これを行うには、Activity を使用して、Utilsという名前のクラスを作成し、次のコードを入れます。

public class Utils{
public static void hideKeyboard(@NonNull Activity activity) {
    // Check if no view has focus:
    View view = activity.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
  }
}

これで、任意のアクティビティでこのメソッドを呼び出すだけで、キーボードを非表示にすることができます

Utils.hideKeyboard(Activity MainActivity.this);
于 2015-02-17T10:48:32.970 に答える