I have an issue when I came back after switching mode either dark/light mode, then the current fragment is null. I want to get back my current fragment (not new fragment) after switching mode/after recreating activity. I am using FragmentStatePagerAdapter. I already tried with InstantiateItem method like this. But I found that the method creates a new fragment. And using SetRetainInstance but, I think SetRetainInstance is not the best way. I already searching the information but, still don't get it. I am using GetItem to declare the fragment inside the adapter. Currently I have 3 tabs/ 3 fragments.
public override Fragment GetItem(int position)
{
switch (position)
{
case 1:
if (fragment1 == null)
{
fragment1 = new FragmentOne(_parentActivity);
}
else
{
fragment1.RefreshPage();
}
return fragment1;
case 2:
if (fragment2 == null)
{
fragment2 = new FragmentTwo(_parentActivity);
}
return fragment2;
case 3:
if (fragment3 == null)
{
fragment3 = new FragmentThree(_parentActivity);
}
else
{
fragment3.fragment3Adapter.UpdateData();
}
return fragment3;
default:
throw new Exception("Unrecognized fragments!!!");
}
}
Then, in the Activity, I am using OnPageSelected(position) to get/know the selected tab/ clicked tab.
public void OnPageSelected(int position)
{
if (position == 1)
{
fragmentAdapter.RefreshPage();
}
else if (position == 3)
{
fragmentAdapter.fragment3.UpdateData();
}
}
Nah, in the OnPageSelected, my Fragment3 is null but the adapter is not null(fragmentAdapter.fragment3.UpdateData();
). And FYI, I dont use FragmentTransaction to switch/get my fragments. So, is there a way to get current fragment without create a new fragment? Please help me! Thank you!