Android - Back button and fragment backstack not working

被刻印的时光 ゝ 提交于 2019-12-03 07:48:38

Check if you are using FragmentActivity(from support library) instead of Activity. This will cause backstack and transition problem.

I'm not sure if this will solve your problem but I dont think you need to add all the fragments to begin with.

I've also noticed (at least with the compatibility library) that the replace method seems to be very buggy, so best to remove the existing fragment first and then add the new one.

Here is the bit of code I use to change a fragment:

/**
 * Changes the detail fragment of this activity. This is how all content is presented in this app.
 * @param fragment
 * @param animated
 * @param addCurrentFragmentToBackStack
 */
private void changeDetailFragment(Fragment fragment,boolean animated,boolean addCurrentFragmentToBackStack)
{
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if (animated)
            transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);

    Fragment currentFrag =  getSupportFragmentManager().findFragmentById(R.id.detailFragment);


    String fragName = "NONE";

    if (currentFrag!=null)
        fragName = currentFrag.getClass().getSimpleName();


    if (currentFrag != null)
    {

        transaction.remove(currentFrag);
    }


    transaction.add(R.id.detailFragment,fragment);


    if (addCurrentFragmentToBackStack)
    {
        Log.i("APP_NAME","Adding: " + fragName + " to the backstack");
        transaction.addToBackStack(null);
    }
    else
    {
        Log.i("APP_NAME","Not adding: " + fragName + " to the backstack");
    }



    transaction.commit();

}

Hope this helps.

For me changing the version of appcompat to 27.1.1(As of 15/08/2018) worked. Turns out appcompat version v7:28.0.0-rc01 was the culprit.

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