【问题标题】:after add a fragment the previous fragment still visible添加片段后,前一个片段仍然可见
【发布时间】:2013-05-24 07:11:15
【问题描述】:

一开始,我使用replace方法将片段添加到返回堆栈,然后我发现当我按下返回键时,堆栈中的片段会再次调用onCreateView,我在api演示中也发现了这种行为,所以我认为这不是一个错误,但我想达到像活动一样的效果,当我 按返回键,上一个活动不会调用onCreate 方法。

后来我发现fragmentManager.add()可以实现我的想法,但是又出现了一个问题,当添加第二个片段时,之前的片段仍然可见。

谁能帮帮我?

FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction2 = manager.beginTransaction();
        transaction2.add(R.id.fl, f2);
        transaction2.addToBackStack("Fragment2");
        transaction2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction2.commit();

【问题讨论】:

    标签: android android-activity fragment


    【解决方案1】:

    回到使用替换并添加一个检查以查看捆绑包是否为空。

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        ...
        if (savedInstanceState == null) {
            // do work 
            // If the view is being recreated this code won't run
        }
        ...
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用“替换”而不是“添加”

      部分代码

      fragmenttransaction.replace(R.id.realtabcontent, Fragment); fragmenttransaction.commit();

      【讨论】:

      • 如果你使用replace,那么当前的fragment会被新的fragment替换,所以当你点击返回时,你不会回到之前的fragment,因为它已经被替换了!
      【解决方案3】:

      检查您是否为片段设置了 argb 背景。在这种情况下,用 rgb 替换该背景。 a 表示透明。

      【讨论】:

        【解决方案4】:

        如果您是第一次添加片段,您可以像在代码中一样添加片段。

        Fragment_Home fragment = new Fragment_Home();
                FragmentTransaction fts = (MainActivity.this).getSupportFragmentManager().beginTransaction();
                fts.add(R.id.frame_container, fragment);
        //        fts.addToBackStack(fragment.getClass().getSimpleName());
                fts.commit();
        

        如果你想从这里移到其他片段,那么你应该用新片段替换当前片段。

        Fragment_CreateGroup fragment = new Fragment_CreateGroup();
                    fts = (MainActivity.this).getSupportFragmentManager().beginTransaction();
        //            fts.addToBackStack(fragment.getClass().getSimpleName());
                    fts.replace(R.id.frame_container, fragment);
                    fts.commit();
        

        这里fts 是定义在顶部的FragmentTransaction 的对象。

        【讨论】:

        • 如果我们再次添加片段会发生什么?上一个还活跃吗??如果在杀死新片段后我们可以回到我们离开片段的前一个片段吗?
        【解决方案5】:

        尝试使用

        manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 
        

        在添加新的FragmentTransaction之前 见here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多