后面堆栈片段空白onbackpressed

时间:2015-05-26 09:27:52

标签: android android-fragments

我有2个片段,当我替换第二个片段并按下后退按钮时,我的第一个片段显示为空白,这是我的代码

    Fragment fragment = new MovieDetails();
            Bundle args = new Bundle();
            args.putString("background", item.getBackg());
            args.putString("thumb", item.getThumb());
            args.putString("id", item.getCode());
            fragment.setArguments(args);
            String backStateName = fragment.getClass().getName();

            boolean fragmentPopped = getActivity()
                    .getSupportFragmentManager().popBackStackImmediate(
                            backStateName, 0);

            if (!fragmentPopped) { // fragment not in back stack, create it.
                FragmentTransaction ft = getActivity()
                        .getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.addToBackStack("TAG");
                ft.commit();
            }
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_frame, fragment).commit();

2 个答案:

答案 0 :(得分:0)

您可以执行此操作

 private void showFragment() {

    final Myfragment fragment = new MyFragment();
    final FragmentTransaction transaction =
    getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
    transaction.addToBackStack(null); 
    transaction.commit(); 
    }

@覆盖

   public void onBackPressed() {
   final Myfragment fragment = (Myfragment)getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);

   if (fragment.allowBackPressed())  {
      super.onBackPressed(); 
   }

答案 1 :(得分:0)

这可能不是你的问题,但它是我的:我过度骑着onSaveInstanceState()而忘了打电话给超级。按下“后退”后,这会产生一个空白片段,几乎可以肯定,因为super.onSaveInstanceState()是片段堆栈保存的地方。