返回堆栈中的碎片不起作用

时间:2017-05-23 11:13:31

标签: java android android-fragments fragment-backstack

我有一个家庭活动,因为我正在根据需要更换片段。

在家庭活动中我有主片段,然后从主片段我替换传输片段,从传输片段我替换TransportList片段。

现在当我从TransportList片段按回来时,我看到主片段而不是传输片段。

我已将片段添加到backstack仍然像这样工作。

家庭活动

public class HomeActivity extends AppCompatActivity{

    private boolean mBackPressCancelled = false;
    private static final long BACK_PRESS_DELAY = 10000;
    private long mBackPressTimestamp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FragmentManager fragmentManager = HomeActivity.this.getFragmentManager();
        MainFragment fragment = new MainFragment();
        fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        fragmentManager.beginTransaction().replace(R.id.mycontainer, fragment,"MAIN_FRAGMENT").commitAllowingStateLoss();

    }

    @Override
    public void onBackPressed() {

        // Do nothing if the back button is disabled.
        if (!mBackPressCancelled) {

            // Pop fragment if the back stack is not empty.

            if (getFragmentManager().getBackStackEntryCount() > 0) {

                mTxtTitle.setVisibility(View.GONE);
                mLogo.setVisibility(View.VISIBLE);

                super.onBackPressed();
            }
            else {
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                long currentTimestamp = System.currentTimeMillis();

                if (currentTimestamp < mBackPressTimestamp + BACK_PRESS_DELAY) {
                    super.onBackPressed();
                } else {
                    mBackPressTimestamp = currentTimestamp;

                    Toast.makeText(this,"press again",Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

传输片段:

       mBtnSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FragmentManager fragmentManager = getFragmentManager();
            TransportListFragment fragment1 = new TransportListFragment();
            fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            fragmentManager.beginTransaction().replace(R.id.mycontainer, fragment1).addToBackStack("G").commit();

        }
    });

这里出了什么问题请帮帮忙。谢谢。

1 个答案:

答案 0 :(得分:1)

将新片段添加到BackStack时,只需删除以下行:

fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);