首页 > 解决方案 > 软键盘不隐藏片段。如何隐藏键盘?

问题描述

我创建了一个BottomSheet使用片段。我的片段包含EditText. 当 EditText 获得焦点时,键盘会自动打开,但在失焦时不会自动关闭/隐藏。当我在片段外部单击时,我想隐藏/关闭键盘,我该BottomSheet如何弄清楚?

这是我的片段类

public class ListItemInputFragment extends BottomSheetDialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final EditText newTaskEt, detailsEt;
        final TextView savBtn;

        View view = inflater.inflate(R.layout.fragment_list_item_input, container, false);

        newTaskEt = view.findViewById(R.id.new_task_et_id);
        detailsEt = view.findViewById(R.id.details_et_id);
        savBtn = view.findViewById(R.id.save_btn_id);

        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

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


        saveButtonClick(savBtn);

        return view;
    }


    private void saveButtonClick(View view) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity().getBaseContext(), "Data Saved.", Toast.LENGTH_SHORT).show();
            }
        });
    }

}

标签: androidfragmentandroid-softkeyboard

解决方案


最后我提出了上述问题的解决方案,这是一种简单易行的方法,我的解决方案是执行我进一步搜索的其他事情。

我只是在我的 res/values/styles.xml 文件中创建一个样式

    <style name="DialogStyle" parent="Theme.Design.Light.BottomSheetDialog">
        <item name="android:windowIsFloating">false</item>
        <item name="android:windowSoftInputMode">adjustResize</item>
    </style>

然后在片段类中我输入以下代码

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
    }

推荐阅读