GetFragmentManager.findFragmentByTag() возвращает null
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
.
Что я пробовал читать другие вопросы:
-
this.setRetainInstance(true)
в oncreate
обоих fragments
.
-
Оба конструктора fragment
пусты public fragmentName(){}
.
-
попробовал executePendingTransactions
после добавления fragments
.
-
попробовал add
вместо replace
на fragments
(отредактирован)
Ответы
Ответ 1
У меня была та же проблема, что и findFragmentByTag(), всегда возвращающая значение null.
В конце концов я отследил его, я переопределял onSaveInstanceState() в своей работе, но не назвал super. Как только я исправил, что findFragmentByTag() вернул фрагмент, как ожидалось.
Ответ 2
Вы можете использовать
fragmentTransaction.addToBackStack(yourFragmentTag);
После этого вы можете повторно использовать его с помощью
getSupportFragmentManager().findFragmentByTag(yourFragmentTag);
Ответ 3
Я смутился об этом в течение долгого времени. Во-первых, вам нужно сохранить фрагмент, который вы заменяете, нажав на задний стек. Тег, который вы поставляете, помещается в добавляемый фрагмент, а не тот, который вы нажимаете на задний стек. Позже, когда вы нажимаете его на задний стек, этот тег идет вместе с ним. Здесь код с разбитыми объектами, чтобы упростить трассировку. Вы должны называть 'addToBackStack' перед 'commit'.
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 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 tag being "GRAPH_FRAGMENT"
Ответ 4
Вызов 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");
Ответ 5
Отвечено здесь, просто нужно позвонить getSupportFragmentManager().executePendingTransactions();
после вашего findByTag или findById
Ответ 6
В моем случае мне пришлось создать объект FragmentManager уровня класса, а затем использовать его, а не напрямую использовать getSupportFragmentManager().
public class Main extends BaseActivity {
FragmentManager fragmentManager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmain);
fragmentManager = getSupportFragmentManager();
initFrag1();
}
private void initFrag1() {
String name = Frag1.class.getSimpleName();
if (fragmentManager.findFragmentByTag(name) == null) {
fragmentManager.beginTransaction()
.add(R.id.frag_container, new Frag1(), name)
.addToBackStack(name)
.commit();
}
}
}