Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Keyboard when Button Click (Fragment)

i got error to implement hide keyboard when button click, anyone know how to fix that? actually code error in getSystemService and getWindowsToken

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_calculator, container, false);

        Button hitung = (Button) rootView.findViewById(R.id.hitung);
        final EditText height = (EditText)rootView.findViewById(R.id.height);
        final EditText weight = (EditText)rootView.findViewById(R.id.weight);

        InputMethodManager imm = InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(EditText.getWindowToken(), 0);

        final TextView result = (TextView)rootView.findViewById(R.id.result);
        final TextView finalresult = (TextView)rootView.findViewById(R.id.finalresult);
        finalresult.setMovementMethod(new ScrollingMovementMethod());

        hitung.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            ..........
}
like image 948
F_X Avatar asked Jan 31 '26 21:01

F_X


1 Answers

you are using Fragment so write like getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)

Reason for the same :

An Activity extends Context, a Fragment does not. Hence, you first need to get a reference to the Activity in which the Fragment is contained

Edit

for the other error you mentioned in the comment you can use

getView().getWindowToken()

and the hide method should be called inside your button's onClick() method like

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

like image 88
Satyen Udeshi Avatar answered Feb 02 '26 11:02

Satyen Udeshi