Search code examples
androidfragmentandroid-fragmentactivityandroid-lifecycle

how to clearfocus after remove a fragment?


problem with the clear focus of an edit text after removing a fragment from the app. bye the way I don't have any problem in android 9 but my real device has android 7 and the problem appears there

   searchFab.setOnClickListener(v -> {
            Fragment fragment = new SearchFragment();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.setCustomAnimations(R.anim.fragment_bottom_up, R.anim.fragment_top_down
                    , R.anim.fragment_bottom_up, R.anim.fragment_top_down);
            transaction.replace(R.id.fragment_area, fragment);
            transaction.addToBackStack(null);
            if (searchEditText.isFocused()) {
                if (searchEditText.getText().toString().equals("")) {
                    inputMethodManager.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
                    searchEditText.clearFocus();
                    searchFabIcon.startAnimation(animationHide);
                    searchFabIcon.setImageResource(R.drawable.ic_search);
                    searchFabIcon.startAnimation(animationShow);
                    getSupportFragmentManager().popBackStack();
                } else {
                    searchEditText.setText("");
                }
            } else {
                transaction.commit();
                searchEditText.requestFocus();
                searchFabIcon.startAnimation(animationHide);
                searchFabIcon.setImageResource(R.drawable.ic_multiply);
                searchFabIcon.startAnimation(animationShow);
                inputMethodManager.showSoftInput(searchEditText,
InputMethodManager.SHOW_IMPLICIT);
            }
        });

Solution

  • Finally I find the answer, only need to add these two lines in your layout xml file. in my case I put them in parent layout and it fix the problem

    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"