S
S
StynuBlizz2017-03-31 16:03:14
Android
StynuBlizz, 2017-03-31 16:03:14

How to handle back button click in android fragments?

Here is the code in the main activity

@Override
    public void onBackPressed() {

        //Обработка нажатия кнопки назад для фрагментов
        FragmentManager fm = getSupportFragmentManager();
        BackPressedForFragments backPressedForFragments = null;
        
        for (Fragment fragment: fm.getFragments()) {
            if (fragment instanceof  BackPressedForFragments) {
                backPressedForFragments = (BackPressedForFragments) fragment;
                break;
            }
        }
        if (backPressedForFragments!=null){
            backPressedForFragments.onBackPressed();
        }

        super.onBackPressed();

    }

Interface
public interface BackPressedForFragments {
     void onBackPressed();
}

And and method overrides inside a fragment
public class PreparationFragment extends Fragment implements BackPressedForFragments
 @Override
    public void onBackPressed() {
        //Код для выполнения
    }

So the problem is that this fragment is located inside another fragment (the subfragment is shorter) and the overridden method is not called from it, but is called from another fragment at all (I think that the getFragments method returns the fragments in the wrong order as I want). In short, How do I handle back button clicks inside fragments? What can you suggest?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question