Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

android fragment addToBackStack(null) :how to add the same fragment to stack just one time?

when fragment use addToBackStack(null) method and click a method many times in an activity, the fragment page will save to back stack everytime, when I press back key, it will restore the same page, how to add the same fragment to stack just one time?

    mSettingBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            SettingFragment settingFragment = new SettingFragment();

            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.replace(R.id.left_framelayout, settingFragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When adding your Fragment to the backstack you should also pass a TAG to be able to identify that Fragment:

 .addToBackStack(SettingsFragment.TAG);

Prior to adding the Fragment you will be able to check if this Fragment is allready in the backstack using :

 getFragmentMangager().findFragmentByTag(SettingsFragment.TAG);

This will return null if the Fragment is not allready added.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...