Joh*_*itt 18 android fragment android-fragments
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);
Run Code Online (Sandbox Code Playgroud)
我提供了一个标签,所以我不确定为什么要findFragmentByTag()返回null.
我在阅读其他问题时尝试过:
this.setRetainInstance(true)在oncreate两者中fragments.
两个fragment构造函数都是空的public fragmentName(){}.
executePendingTransactions加入后尝试了fragments.
尝试add而不是replace在fragments(编)
小智 16
很长一段时间我对此感到困惑.首先,您需要将要替换的片段保存到后台堆栈中.您提供的标签放在要添加的片段上,而不是您要推送到后台堆栈的片段上.之后,当你把它推到后面的堆栈上时,那个标签就随之而来.这里的代码分解为对象,以便于跟踪.你必须在'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"
Run Code Online (Sandbox Code Playgroud)
tag*_*y22 15
我遇到了findFragmentByTag()总是返回null的问题.
最终我追踪了它,我onSaveInstanceState()在我的活动中压倒一切,但没有打电话给超级.一旦我修复了,findFragmentByTag()就像预期的那样返回了Fragment.
片段事务后调用getFragmentManager().executePendingTransactions().
getFragmentManager()
.beginTransaction()
.replace(R.id.container, new ExampleFragment(), "YOUR TAG HERE");
.commit();
//after transaction you must call the executePendingTransaction
getFragmentManager().executePendingTransactions();
//now you can get fragment which is added with tag
ExampleFragment exampleFragment = getFragmentManager().findFragmentByTag("YOUR TAG HERE");
Run Code Online (Sandbox Code Playgroud)
您可以使用
fragmentTransaction.addToBackStack(yourFragmentTag);
Run Code Online (Sandbox Code Playgroud)
之后,您可以重复使用它
getSupportFragmentManager().findFragmentByTag(yourFragmentTag);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20846 次 |
| 最近记录: |