【问题标题】:FragmentTransaction add() behaviorFragmentTransaction add() 行为
【发布时间】:2015-01-13 14:44:19
【问题描述】:

使用片段我一直使用replace() 处理我的事务,但我希望我不必再保存实例状态来恢复片段的视图并防止在返回该片段时重新加载。所以,我决定与add() 合作。问题是当我添加另一个片段时,前一个片段视图保留在后台,这很好(这是我所期望的行为),但问题是我实际上可以与后台视图交互。 示例:

片段 A 有一个 Button

片段 B 有一个 TextView

当我添加 Fragment A 后添加 Fragment B 时,我可以点击 Fragment A's Button,甚至停留在 Fragment B 的 视图上。

我正在使用:

FragmentTransaction fragmentTransaction = 
            getSupportFragmentManager().beginTransaction().
            add(getRootViewContainer(),fragment,fragment.getClass().getSimpleName());

if (shouldGoBack) 
    fragmentTransaction.addToBackStack(fragment.getClass().getSimpleName());

其中getRootViewContainer() 返回我用作活动主容器的FrameLayoutid

现在,这真的是add() 的默认行为吗?

如果是这样,是否有适当的方法来避免这种情况,或者只需要使用replace()

【问题讨论】:

  • 您找到解决方案了吗?如果你还没有,试试下面的一些。我确信我的会工作,因为我自己使用它。

标签: android android-layout android-activity android-fragments fragmenttransaction


【解决方案1】:

你可以在这里做的只是在当前片段的交易时隐藏之前的片段。

 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  Fragment newFragment= new MyFragment ();
  ft.hide(CurrentFragment.this);
  ft.show(newFragment);
  ft.commit();

对我有用,试试吧。

【讨论】:

    【解决方案2】:
    FragmentTransaction.hide(fragmentBehind); //works for me!
    

    示例:

    //I have it globally available
    FragmentTransaction trans = MainActivity.getManager().beginTransaction(); 
    
    //not globally 
    FragmentTransaction trans = getFragmentManager().beginTransaction();
    MapFragment newFragment = new newFragment();
    trans.add(R.id.fragmentContainer, newFragment, tag);
    trans.hide(this);
    trans.addToBackStack(tag);
    trans.commit();
    

    【讨论】:

    • 您好,抱歉耽搁了。我正在使用这种隐藏和显示片段的方法,但我想避免这种当我必须显示一个或隐藏另一个时的事情。你知道我们还有其他方法可以做到吗?谢谢。
    • 禁用焦点后面的布局?我真的不知道任何其他干净的方式。这种方法最适合我,我使用了大约 15 种不同的片段。如果我愿意,我可以拥有 100 多个片段,但由于上面的功能,一切都很顺利。
    【解决方案3】:

    是的,这是 add() 的默认行为。 如果您真的不想使用 replace(),您可以尝试禁用“旧”片段内的视图。

    【讨论】:

      猜你喜欢
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多