91

我有一个FragmentActivity使用 aViewPager来服务几个片段。每个都是ListFragment具有以下布局的:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp">
        <ListView android:id="@id/android:list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

        <EditText android:id="@+id/entertext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

启动活动时,软键盘显示。为了解决这个问题,我在片段中执行了以下操作:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //Save the container view so we can access the window token
    viewContainer = container;
    //get the input method manager service
    imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    . . .
}

@Override
public void onStart() {
    super.onStart();

    //Hide the soft keyboard
    imm.hideSoftInputFromWindow(viewContainer.getWindowToken(), 0);
}

我将传入的ViewGroup container参数保存onCreateView为访问主要活动的窗口令牌的一种方式。这运行没有错误,但键盘不会在调用hideSoftInputFromWindowin 时隐藏onStart

最初,我尝试使用膨胀布局而不是container,即:

imm.hideSoftInputFromWindow(myInflatedLayout.getWindowToken(), 0);

但这抛出了一个NullPointerException,大概是因为片段本身不是一个活动并且没有唯一的窗口令牌?

有没有办法从片段中隐藏软键盘,或者我应该在片段中创建一个方法FragmentActivity并从片段中调用它?

4

18 回答 18

196

只要您的 Fragment 创建一个视图,您就可以在附加视图使用该视图中的 IBinder(窗口令牌) 。例如,您可以在 Fragment 中覆盖 onActivityCreated:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
于 2012-04-02T18:41:12.857 回答
87

除了以下代码行对我有用:

getActivity().getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
于 2014-05-29T13:33:28.680 回答
23

如果您将以下属性添加到 Activity 的清单定义中,它将完全抑制键盘在您的 Activity 打开时弹出。希望这会有所帮助:

(添加到您的 Activity 的清单定义中):

android:windowSoftInputMode="stateHidden"
于 2011-11-09T17:28:53.983 回答
14
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_my, container,
                false);
        someClass.onCreate(rootView);
        return rootView;
    }

在我的班级中保留我的根视图的实例

View view;

public void onCreate(View rootView) {
    view = rootView;

使用视图隐藏键盘

 public void removePhoneKeypad() {
    InputMethodManager inputManager = (InputMethodManager) view
            .getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    IBinder binder = view.getWindowToken();
    inputManager.hideSoftInputFromWindow(binder,
            InputMethodManager.HIDE_NOT_ALWAYS);
}
于 2015-05-12T14:25:46.737 回答
11

但例外情况是,必须隐藏DialogFragment嵌入的焦点,而只能隐藏嵌入的第一个焦点DialogEditTextDialog

this.getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
于 2013-12-11T19:13:33.370 回答
9

此代码适用于片段:

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
于 2017-07-19T09:27:58.223 回答
5

在您喜欢的任何地方(活动/片段)使用此静态方法。

public static void hideKeyboard(Activity activity) {
    try{
        InputMethodManager inputManager = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        View currentFocusedView = activity.getCurrentFocus();
        if (currentFocusedView != null) {
            inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

如果您想用于片段,只需调用hideKeyboard(((Activity) getActivity())).

于 2018-07-14T16:01:09.383 回答
3

当我在标签中从一个片段切换到另一个片段时,这将适用于我的情况

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        try {
            InputMethodManager mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            mImm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
            mImm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            Log.e(TAG, "setUserVisibleHint: ", e);
        }
    }
}
于 2018-08-17T07:03:17.907 回答
2

这对 API27 不起作用。我必须在布局的容器中添加它,对我来说它是一个 ConstraintLayout:

<android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:focusedByDefault="true">

//Your layout

</android.support.constraint.ConstraintLayout>
于 2018-07-07T10:29:50.883 回答
2

这在 Kotlin 课程中对我有用

fun hideKeyboard(activity: Activity) {
    try {
        val inputManager = activity
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val currentFocusedView = activity.currentFocus
        if (currentFocusedView != null) {
            inputManager.hideSoftInputFromWindow(currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

}
于 2020-01-05T17:41:06.660 回答
2

在片段中对我有用的解决方案:

fun hideKeyboard(){
    val imm = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view?.windowToken, 0)
}

并在一项活动中:

fun hideKeyboard(){
    val inputManager: InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputManager.hideSoftInputFromWindow(currentFocus?.windowToken, InputMethodManager.SHOW_FORCED)
}
于 2021-08-05T10:33:26.627 回答
1

在任何片段按钮侦听器中使用此代码:

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
于 2020-05-16T13:41:07.707 回答
1

科特林代码

val imm = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(requireActivity().currentFocus?.windowToken, 0)
于 2021-01-02T06:19:44.507 回答
0

只需在您的代码中添加这一行:

getActivity().getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
于 2018-09-19T10:48:22.737 回答
0

在科特林:

(activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(view?.windowToken,0)
于 2019-05-18T06:56:48.153 回答
0

用这个:

Button loginBtn = view.findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
   }
});
于 2020-09-11T02:52:23.103 回答
0

开始

在片段中,下面的代码(在 onActivityCreated 中使用)强制在开头隐藏键盘:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Objects.requireNonNull(getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}

在片段期间(如果需要)

并且如果您有edittext或其他不同需求的键盘,并且想要在键盘外按下时隐藏键盘(在我的情况下,我在xml中有LinearLayout类),首先初始化布局:

LinearLayout linearLayout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
    View view = inflater.inflate(R.layout.<your fragment xml>, container, false);

    linearLayout= view.findViewById(R.id.linearLayout);
    ...
    return view;
}

然后,您需要以下代码(在 onViewCreated 中使用):

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

    linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view12) {
            try {
                InputMethodManager inputMethodManager = (InputMethodManager) Objects.requireNonNull(VideoFragment.this.getActivity()).getSystemService(INPUT_METHOD_SERVICE);
                assert inputMethodManager != null;
                inputMethodManager.hideSoftInputFromWindow(VideoFragment.this.getActivity().getCurrentFocus().getWindowToken(), 0);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}
于 2021-01-13T14:53:08.470 回答
0

您可以使用两种方式:

您可以在片段内创建一个方法,但首先您必须创建一个 View 属性并将充气结果放入其中,然后再返回 onCreateView:

1° 打开你的 Fragment 课程。创建属性

private View view;

2° 在 onCreateView 中为充气机分配“视图”属性

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
                view = inflater.inflate(R.layout.your_activity_main, container, false);
                return view;
}

3°创建方法'hideKeyboard'

public void hideKeyboard(Activity activity) {
        try{
            InputMethodManager inputManager = (InputMethodManager) activity
                    .getSystemService(view.getContext().INPUT_METHOD_SERVICE);
            View currentFocusedView = activity.getCurrentFocus();
            if (currentFocusedView != null) {
                inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

5° 现在只需调用方法

    hideKeyboard(getActivity());

如果这不能解决您的问题,您可以尝试将 MainActivity 类作为对象传递以关闭 Frament 类中的键盘

1° 在您实例化 Fragment 的 YourClassActivity 中,创建方法“hideKeyboard”

public class YourClassActivity extends AppCompatActivity {
    public static void hideKeyboard(Activity activity) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            //Find the currently focused view, so we can grab the correct window token from it.
            View view = activity.getCurrentFocus();
            //If no view currently has focus, create a new one, just so we can grab a window token from it
            if (view == null) {
                view = new View(activity);
            }
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
}

2°在你的Activity中实现'Serializable'接口来实例化Fragment

public class YourClassActivity extends AppCompatActivity implements Serializable {
...
}

3° 当你在Activity中实例化Fragment时,你必须将参数传递给那个Fragment,这将是Activity类本身

Bundle bundle = new Bundle();
bundle.putSerializable("activity", this);
YourClassFragment fragment = new YourClassFragment();
fragment.setArguments(bundle);

4° 现在让我们上你的 Fragment 课程。创建属性视图和活动。

private View view;  
private Activity activity;

5° 在 onCreateView 中为充气机分配“视图”属性。在这里,您将检索作为此 Fragment 的参数传递的 Activity 对象

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            view = inflater.inflate(R.layout.your_activity_main, container, false);
            activity = (Activity) getArguments().getSerializable("obj");
    
            return view;
    }

6° 现在只需调用方法

hideKeyboard(activity);
于 2021-07-31T01:32:28.407 回答