I have a FragmentActivity
using a ViewPager
to serve several fragments. Each is a ListFragment
with the following layout:
Nothing of this worked on API27. I had to add this in the container of the layout, for me it was a 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>
Use this code in any fragment button listener:
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
Use this:
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);
}
});
In Kotlin:
(activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(view?.windowToken,0)
Exception for DialogFragment
though, focus of the embedded Dialog
must be hidden, instead only the first EditText
within the embedded Dialog
this.getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
@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;
}
Keep an instance of my root view in my class
View view;
public void onCreate(View rootView) {
view = rootView;
Use the view to hide the keyboard
public void removePhoneKeypad() {
InputMethodManager inputManager = (InputMethodManager) view
.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
IBinder binder = view.getWindowToken();
inputManager.hideSoftInputFromWindow(binder,
InputMethodManager.HIDE_NOT_ALWAYS);
}