【问题标题】:Fragment is not showing up in view for duplicate dynamic added fragment对于重复的动态添加片段,片段未显示在视图中
【发布时间】:2016-02-20 07:58:48
【问题描述】:

我有以下片段设置:

12 是分别包含 AB 片段的选项卡。 A中有一个按钮,点击后显示C

工作正常:在第一个标签1 中,A 是通过 xml 静态添加的。单击该按钮后,C 启动正常,按下后退按钮让我回到A

|__1__|  2  |
|  A  |  B  |
   ↓
|  C  |

失败:在B中,有一个按钮可以动态打开A。现在在A 中按下与前一个案例相同的按钮,但在此视图中,C 失败 显示。我可以在 adb 中看到数据加载正常,但不知何故它不在视图中。

|  1  |__2__|
|  A  |  B  |
         ↓
      |  A  |
         ↓
      |  C  |

我的按钮代码从AC 是:

@Override
public void onReshareTextClick(View v, int position) {
    this.getFragmentManager().beginTransaction().replace(R.id.feedContent,
            LikeReshareFragment.newInstance(feedAdapter.getFeedItem(position), Utils
                    .FragmentType.Reshare))
                    .addToBackStack(null).commit();
}

BA 的代码是:

@Override
public void onPhotoClick(View v, int position) {
    this.getFragmentManager().beginTransaction().replace(R.id.llMySnaps,
            FeedFragment.getInstance(sharedFeedItems))
            .addToBackStack(null).commit();
}

问题:因为有两个同名的片段,我怀疑这行在标签2 中有问题replace(R.id.feedContent,..。它实际上可能正在替换选项卡1(不可见)中的A,而不是选项卡2 中的那个。这是否正确和/或如何解决?

更新 我可以确认上述说法。 C 实际上显示在标签1 中。为什么会这样?由于android有两个A(常量idR.id.feedContent)可供选择,我如何明确使用B启动的那个?

【问题讨论】:

    标签: android android-fragments fragmentmanager


    【解决方案1】:

    问题是 Android 在 R.id.feedContent 上执行 DFS 以查找要在事务中替换的视图。

    解决方案 通过以编程方式将ID 分配给视图,我能够找到 要替换的正确视图。

    设置视图 ID:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_feed, container, false);
        CoordinatorLayout coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id.feedContent);
        coordinatorLayout.setId(feedID+10); // here feedID is what differentiates the two feed fragments
    
        return view;
    }
    

    这里是替换片段的调用:

    this.getFragmentManager().beginTransaction().replace(feedID+10, openPostFragment)
                    .addToBackStack(null).commit();
    

    【讨论】:

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