Android Fragment回退栈的使用

现有这样一个场景,从Fragment1跳转到Fragment2再跳转到Fragment3,

如何实现按下回退键直接从Fragment3返回Fragment1?

利用FragmentManager的getBackStackEntryCount() 来获取当前回退栈中Fragment的个数

如果大于1就循环弹出栈顶fragment

具体代码实现

public class FragmentActivity extends AppCompatActivity implements OnReplace {

    private FrameLayout frameLayout;

    private BlankFragment blankFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);
        frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        blankFragment  = new BlankFragment();
        transaction.add(R.id.frameLayout, blankFragment);
        transaction.commit();
    }

    @Override
    public void onBackPressed() {
        // 获取当前回退栈中的Fragment个数
        int backStackEntryCount = fragmentManager.getBackStackEntryCount();
        //如果大于1 就做循环回退
        if (backStackEntryCount > 1) {
            while (fragmentManager.getBackStackEntryCount() > 0) {
                super.onBackPressed();
            }
        }
    }

    private FragmentManager fragmentManager;


    @Override
    public void onReplace(int index) {
        final BlankFragment2 blankFragment2 = new BlankFragment2();
        final BlankFragment3 blankFragment3 = new BlankFragment3();
        switch (index) {
            case 1:
                fragmentManager.beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.frameLayout,blankFragment2)
                        .commit();
                break;
            case 2:
                fragmentManager.beginTransaction()
                        .replace(R.id.frameLayout,blankFragment3)
                        .addToBackStack(null)
                        .commit();

                break;
        }
    }


}



你可能感兴趣的:(Android)