gpt4 book ai didi

android - GetFragmentManager.findFragmentByTag() 返回 null

转载 作者:IT王子 更新时间:2023-10-28 23:34:54 29 4
gpt4 key购买 nike

        getFragmentManager().beginTransaction()
.replace(R.id.graph_fragment_holder, new GraphFragment(), "GRAPH_FRAGMENT")
.commit();

getFragmentManager().beginTransaction()
.replace(R.id.list_fragment_holder, new ListFragment(), "LIST_FRAGMENT")
.commit();

//getFragmentManager().executePendingTransactions();

GraphFragment graphFragment = (GraphFragment) getFragmentManager().findFragmentByTag("GRAPH_FRAGMENT");
graphFragment.setData(data);

ListFragment listFragment = (ListFragment) getFragmentManager().findFragmentByTag("LIST_FRAGMENT");
listFragment.setData(data);

我提供了一个标签,所以我不确定为什么 findFragmentByTag() 返回 null

我通过阅读其他问题的尝试:

  1. this.setRetainInstance(true) 在两个 fragmentsoncreate 中。

  2. 两个 fragment 构造函数都是空的 public fragmentName(){}

  3. 在添加 fragments 后尝试了 executePendingTransactions

  4. fragments 上尝试了 add 而不是 replace(已编辑)

最佳答案

我为此困惑了很长时间。首先,您需要通过将要替换的 fragment 插入后堆栈来保存它。您提供的标签放在您正在添加的 fragment 上,而不是您正在到后台堆栈的 fragment 上。稍后,当您将其推送到后堆栈时,该标签随之而来。这是带有分解对象的代码,以便于跟踪。您必须在 'commit' 之前调用 'addToBackStack'。

GraphFragment grFrag = new GraphFragment();
FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
tr.replace(R.id.fragment_container, grFrag, "GRAPH_FRAGMENT");
// grFrag is about to become the current fragment, with the tag "GRAPH_FRAGMENT"
tr.addToBackStack(null);
// 'addToBackStack' also takes a string, which can be null, but this is not the tag
tr.commit();
// any previous fragment has now been pushed to the back stack, with it's tag

ListFragment liFrag = new ListFragment();
FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
tr.replace(R.id.fragment_container, liFrag, "LIST_FRAGMENT");
// liFrag is is about to become the current fragment, with the tag "LIST_FRAGMENT"
tr.addToBackStack(null);
tr.commit();
// 'grFrag' has now been pushed to the back stack, with it's tag being "GRAPH_FRAGMENT"

关于android - GetFragmentManager.findFragmentByTag() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23581894/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com