Search code examples
androidfragmentandroid-softkeyboard

Soft keyboard not hiding from fragment. How to hide keyboard?


I have created a BottomSheet using fragment. My fragment contains EditText. The keyboard opens automatically when the EditText is focused but it doesn't close/hide automatically when it's out of focus. I want to hide/close the keyboard when I click outside of the BottomSheet fragment, How can I figure it out?

This is my fragment class

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

}

Solution

  • finally i came out with the solution of above problem this is a simple and easy way to do this by the way my solution is perform another things that i searching further.

    i just create a style in my res/values/styles.xml file

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

    and then inside the fragment class i put the following code

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