在片段替换时显示/隐藏Android软键盘

Man*_*iac 23 android fragment android-softkeyboard android-fragments

我有一个片段活动.让我们说一个包含事物列表的列表片段.现在我想让用户添加一个东西,所以我使用FragmentManager用一个带有EditText的插入片段替换列表片段.EditText具有焦点,光标闪烁.但软键盘无法打开.反之亦然:如果用户输入了新内容并将其添加到列表中,我将插入片段替换为列表片段.但是,虽然没有EditText,键盘也不会关闭.

实现这个的正确方法是什么?我不敢相信我必须在所有过渡时手动显示和隐藏键盘?!

Jer*_*all 5

显示键盘:

editText.requestFocus();
InputMethodManager keyboard = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(editText, 0);
Run Code Online (Sandbox Code Playgroud)

然后将其隐藏:

InputMethodManager keyboard = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.hideSoftInputFromWindow(editText.getWindowToken(), 0);
Run Code Online (Sandbox Code Playgroud)


bpa*_*ski 5



想做的事情:1.扩展Fragment
2.覆盖onAttach()onDetach()回调
3.实现显示和隐藏软件键盘方法

示例代码:

class MyFragment extends Fragment {
   @Override
   public void onAttach(Activity activity) {
       super.onAttach(activity);

       //show keyboard when any fragment of this class has been attached
       showSoftwareKeyboard(true);
   }

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

       //hide keyboard when any fragment of this class has been detached
       showSoftwareKeyboard(false);
   }

   protected void showSoftwareKeyboard(boolean showKeyboard){
       final Activity activity = getActivity();
       final InputMethodManager inputManager = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);

       inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), showKeyboard ? InputMethodManager.SHOW_FORCED : InputMethodManager.HIDE_NOT_ALWAYS);
   }
}
Run Code Online (Sandbox Code Playgroud)


Boj*_*man 0

我猜你ListView正在抢走你的焦点EditText,试试这个,让我知道是否有帮助。

getListView().setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
Run Code Online (Sandbox Code Playgroud)