Skip some fragments onBackPressed

前端 未结 3 1495
[愿得一人]
[愿得一人] 2021-02-05 16:28

I am fairly new with android fragments so please bear with me.

I have a bunch of fragments using a single activity as host.

In my mind, my fragments are grouped

3条回答
  •  故里飘歌
    2021-02-05 16:50

    You could try this, it should work and doesnt give a split-second delay. Its not beautiful code though, and if somebody has a better way, please post.

    1.Give a tag to your fragments.

    transaction.add(R.id.main_activity_container, FirstFragment, "FirstFragment");
    transaction.replace(R.id.main_activity_container, Second, "SECOND");
    transaction.replace(R.id.main_activity_container, Third, "THIRD");
    

    2.Modify your onBackPressed() in your frameActivity (activity) that "houses" your fragments.

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
    
        int lastStack = getSupportFragmentManager().getBackStackEntryCount();
        try {
            //If the last fragment was named/tagged "three"
            if (getSupportFragmentManager().getFragments().get(lastStack).getTag().equalsIgnoreCase("THIRD")){
    
                getSupportFragmentManager().popBackStackImmediate();
                getSupportFragmentManager().popBackStackImmediate();
    
                //Get your first fragment that you loaded in the beginning. 
                Fragment first = getSupportFragmentManager().findFragmentByTag("FirstFragment");
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.main_activity_container, first);
                transaction.commit();
                return;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        super.onBackPressed();
    }
    

提交回复
热议问题