Listener for when a Fragment becomes visible

主宰稳场 提交于 2019-12-12 16:41:11

问题


I'm going crazy trying to get an optionsMenu to have different options for different views. I could have it working if onResume() was called on my fragments, but it isn't.

I have one SherlockFragmentActivity which during onCreate adds a SherlockFragment like this:

if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
            Fragment f = LoginFragment.newInstance();

            getSupportFragmentManager()
                    .beginTransaction()
                    .add(android.R.id.content, f, "loginfragment")
                    .attach(f)
                    .commit();
        }

This eventually adds another SherlockFragment on top of it using the same method:

Fragment f = OfferListFragment.newInstance();
        getActivity().getSupportFragmentManager()
                .beginTransaction()
                .add(android.R.id.content, f, "offerList")
                .addToBackStack(f.getClass().getSimpleName())
                .commit();

and finally this launches yet another SherlockFragment on top using the method:

AddOfferFragment newFragment = AddOfferFragment.newInstance(offer);

        getActivity()
                .getSupportFragmentManager()
                .beginTransaction()
                .add(android.R.id.content, newFragment, "addofferdialog")
                .addToBackStack(newFragment.getClass().getSimpleName())
                .commit();

I've added onResume() events like so:

@Override
    public void onResume() {
        Log.e(TAG, "onResume");
        super.onResume();
    }

now I see onResume logs when they are created, but when I pressBackfrom any of them, I don't get theonResume` log's at all. 1 of my options is to logout which dismisses all views like this:

FragmentManager fm = getSupportFragmentManager();

        if (fm.getBackStackEntryCount() > 0) {
            fm.popBackStack(fm.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }

but I don't even get onResume on the very first fragment.

Due to another issue I have with the fragments being transparent here (This may be normal behaviour, i'm not sure). I'm wondering if the way I am adding the fragments is wrong?

If not, what else could be the problem?


回答1:


As noted by JonasSeputis and the OP himself, the solution was to change the transaction.add() to transaction.replace()

The detailed solution is here.



来源:https://stackoverflow.com/questions/16594352/listener-for-when-a-fragment-becomes-visible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!