To show DialogFragment, I can use below two ways:
ProgressDialogFragment fragment = (ProgressDialogFragment) getFragmentManager().findFragmentByTag("progress_dialog");
if (fragment == null) {
fragment = ProgressDialogFragment.newInstance();
fragment.setCancelable(false);
getFragmentManager().beginTransaction()
.add(fragment, "progress_dialog")
.commitAllowingStateLoss();
}
or
ProgressDialogFragment fragment = (ProgressDialogFragment) getFragmentManager().findFragmentByTag("progress_dialog");
if (fragment == null) {
fragment.show(getFragmentManager().beginTransaction(), "progress_dialog");
}
When and which I should use? Or both are same?
there are pretty much the same. show retrieve a transaction, from the FragmentManager you provide as parameter, and call add/commit as you can see from the snippet
public void show(FragmentManager manager, String tag) {
mDismissed = false;
mShownByMe = true;
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commit();
}
the only difference is they reset some flags upon multiple calls of show()
I am trying to save fragment state in onSaveInstanceState but when i go back to fragment, it always reloaded again instead of starting from last state.
I looked into onCreateView and onActivityCreated and it always have onSaveInstanceState as null.
public void navigateFragment(String tag, Fragment fragment,
boolean shouldAdd) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (shouldAdd)
mStacks.get(tag).push(fragment); // push fragment on stack
ft.replace(android.R.id.tabcontent, fragment);
if (shouldAdd)
ft.addToBackStack(tag);
ft.commit();
}
As i am unable to use backstack because in tabs back stack is not useful. Any help would be highly appreciated.
In this case you have to manage fragments' states by yourself. I don't know exactly how your code works so the only thing I can do is to give you some hints.
The first thing you need to implement is saving fragment's state. Let's assume that all fragments have unique ids. In this case you need to create a map that will keep all the states:
private final Map<String, Fragment.SavedState> mFragmentStates = new HashMap<>();
private void saveFragmentState(String id, Fragment fragment) {
Fragment.SavedState fragmentState =
getSupportFragmentManager().saveFragmentInstanceState(fragment);
mFragmentStates.put(id, fragmentState);
}
You need to call this method for a fragment that you're going to remove. Then we need to restore fragment's state and that's how we can do it:
private void restoreFragmentState(String id, Fragment fragment) {
Fragment.SavedState fragmentState = mFragmentStates.remove(id);
if (fragmentState != null) {
fragment.setInitialSavedState(savedState);
}
}
This method you need to call before adding a fragment to a transaction.
The code provided should work fine but to make it work correctly on activity recreation we need to save and restore mFragmentStates properly:
private static final String KEY_FRAGMENT_STATES = "fragment_states";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Your code ... */
if (savedInstanceState != null) {
Bundle fragmentStates =
savedInstanceState.getParcelable(KEY_FRAGMENT_STATES);
if (fragmentStates != null) {
for (String id : fragmentStates.keySet()) {
Fragment.SavedState fragmentState =
fragmentStates.getParcelable(id);
mFragmentStates.put(id, fragmentState);
}
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/* Your code ... */
Bundle fragmentStates = new Bundle(mFragmentStates.size());
for (Map.Entry<String, Fragment.SavedState> entry : mFragmentStates.entrySet()) {
fragmentStates.put(entry.getKey(), entry.getValue());
}
outState.putParcelable(KEY_FRAGMENT_STATES, fragmentStates);
}
Also you can take a look at FragmentStatePagerAdapter class. It uses the same approach for managing states of ViewPager's fragments.
UPDATE: And so your code should end up looking something like this:
private Fragment mCurrentFragment;
public void navigateFragment(String tag, Fragment fragment,
boolean shouldAdd) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
if (shouldAdd) {
mStacks.get(tag).push(fragment); // push fragment on stack
}
if (mCurrentFragment != null) {
saveFragmentState(mCurrentFragment.getClass().getName(), mCurrentFragment);
}
mCurrentFragment = fragment;
restoreFragmentState(fragment.getClass().getName(), fragment);
transaction.replace(android.R.id.tabcontent, fragment);
if (shouldAdd) {
// You shouldn't use back-stack when managing fragment states by yourself.
transaction.addToBackStack(tag);
}
transaction.commit();
}
In this example I use fragment's class name as an id so all the fragment must have different classes. But you can use any other unique value as an id. And another important thing I have to mention is that you shouldn't use back-stack when managing fragment states by yourself. Back-stack performs similar state management and you will likely have conflicts.
I think you should use the idea of Shared Preferences, this is faster than using local files or database, and definitely easier to code. A good Android webpage # Storage Options. I'll put some sample code from the webpage and change a few to fit your needs.
First, get the data saved from preferences in onCreate() override method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
...
}
Next let's save data before the fragment stops or exits, for various reasons. Achieve this by override onDetach method, the webpage override onStop() instead.
#Override
public void onDetach() {
super.onDetach();
...
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
Good luck, have fun!
You are doing replace fragment, thats why fragment is getting destroyed. You can try below. Here i am doing two things in single FragmentTransaction, i am adding a new fragment & hiding the existing fragment.
Lets say we are adding fragment B on top of Fragment A
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(android.R.id.tabcontent, fragmentB, tagFragmentB)
.hide(fragmentManager.findFragmentByTag(tagFragmentA))
.addToBackStack(tag)
.commit();
Once you do back press, it will remove the fragment B & show the fragment A with same state(before you added fragment B)
Please note here tagFragmentA & tagFragmentB are tags with which fragments A & B are added respectively
clearBackStackEntry();
rl.setVisibility(View.GONE);
getSupportFragmentManager().beginTransaction()
.replace(FRAGMENT_CONTAINER, new HomeScreen())
.addToBackStack(null).commit();
private void clearBackStackEntry() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count > 0) {
getSupportFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
TRY THIS AND One more for fragment also try this: but use support.v4.app.Fragment, May be it will help you
Fragment fr = new main();
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager()
.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
// getActivity().finish();
declare
setRetainInstance(true)
In your fragment onCreate(). to recreate previous state
And link will helpful for understanding for how setRetainInstance work.
Understanding Fragment's setRetainInstance(boolean)
Why use Fragment#setRetainInstance(boolean)?
Thanks :)
it is very simple to handle these things. I can give you the sample to handle the back press on Fr agents which we added.
I have declared a fragment stack and push all the fragments in it like;
public static Stack<Fragment> fragmentStack;
make a method like this:
public static void replaceFragementsClick(Fragment fragementObj, Bundle bundleObj, String title){
try {
FragmentManager fragmentManager = ((FragmentActivity) mContext).getSupportFragmentManager();
if (fragementObj != null) {
fragementObj.setArguments(bundleObj);
fragmentManager.beginTransaction().replace(R.id.frame_container, fragementObj).commit();
}
DashBoardActivity.fragmentStack.push(fragementObj);
} catch (Exception e) {
e.printStackTrace();
}
}
Try this one also:
public static void replaceFragementsClickBack(Fragment fragementObj, Bundle bundleObj, String title){
try {
FragmentManager fragmentManager = ((FragmentActivity) mContext).getSupportFragmentManager();
if (fragementObj != null) {
fragementObj.setArguments(bundleObj);
fragmentManager.beginTransaction().replace(R.id.frame_container, fragementObj).commit();
DashBoardActivity.fragmentStack.pop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
In the base activity where you have added, override the backpressed like:
#Override
public void onBackPressed() {
/**
* Do Current Fragment Pop
* */
fragmentStack.pop();
if(fragmentStack.size() >0){
Bundle bunldeObj = new Bundle();
//******Exit from Current Fragment
Fragment fragment = fragmentStack.pop();
// fragmentStack.push(fragment);
if(fragment instanceof PhotosFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Photos");
}else if(fragment instanceof PhotoDetatilFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Photos");
}else if(fragment instanceof PhotoFullViewFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Photos");
}else if(fragment instanceof HomeFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Home");
}else if(fragment instanceof VideosFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Videos");
}else if(fragment instanceof VideoDetailFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Videos");
}else if(fragment instanceof VideoViewFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Videos");
}else if(fragment instanceof MusicFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Music");
}else if(fragment instanceof MusicListFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Music");
}else if(fragment instanceof InstallAppsFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Apps");
}else if(fragment instanceof MessageFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Messages");
}else if(fragment instanceof MessageDetailFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Messages");
}else if(fragment instanceof LocateDeviceFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Locate Device");
}else if(fragment instanceof FilesFragmentBottomBar){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Files");
}else if(fragment instanceof AppsFragment){
bunldeObj.putString("position", "4");
replaceFragementsClick(fragment,bunldeObj,"Apps");
}else {
super.onBackPressed();
Intent intent = new Intent(DashBoardActivity.this,ConnectDeviceActivity.class);
startActivity(intent);
finish();
}
}
I am not clear of way kind of vie you are using for implementing Tabs.
I guessed from,
ft.replace(android.R.id.tabcontent, fragment);
that you might have implemented FragmentTabHost.
write a customFragmentTabhost and override
#Override
public void onTabChanged(String tabId) {
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
if (tabId.equals(“Tab1”)) {
TabFragment1 fragment1 = null;
if (getSupportFragmentManager().findFragmentByTag(“Tab1”) == null) {
fragment1 = new TabFragment1();
} else {
fragment1 = (TabFragment1) getSupportFragmentManager().findFragmentByTag("Tab1");
}
t.replace(R.id.realContent, fragment1, "Tab1").addToBackStack(null).commit();
}
}
UPDATE:
Ensure Activity is not recreated on orientation, If so setRetainInstance(true), so that even if activity is recreated on orientation change, the fragments will be retained.
Do give id for any views in the fragment. It is important for Android system to maintain state.
I have something like this inside my activity:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment = null;
switch (position+1) {
case 1: {
fragment = new Fragment_Login();
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.container, fragment)
.commit();
break;
}
case 2: {
SwipeRefreshListFragment swipeFragment = new Fragment_List_Of_Assessments();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, swipeFragment)
.commit();
break;
}
case 3: {
fragment = new Fragment_Report();
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.container, fragment)
.commit();
break;
}
case 4: {
fragment = new Fragment_Settings();
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.container, fragment)
.commit();
break;
}
default:
break;
}
}
The program automatically loads case1, but when case2 is selected, getSupportFragmentManager loads the Fragment on top of case1. I guess there are some problem with using both supportFragmentManager and FragmentManager. They seem to have their own stack. The problem is that I cannot use only either one of them because the SwipeToRefresh Android example uses ListView which needs support.v4.Fragment which needs the old FragmentManager. So how is it possible to integrate both FragmentManagers together?
I have accomplished something like this when using PreferenceFragment (not supported by support library version). In order to achieve this I kept inside my Activity a pair of boolean (isLastFragmentSupportType and lastFragmentShowed) and also a String (lastFragmentTag).
At the beginning your Activity will have both of them to false. And when you add a new Fragment you use these 2 boolean to know if you need to clean the other FragmentManager or not. I'll use your code as an example:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment = null;
switch (position+1) {
case 1: {
if(isLastFragmentSupportType && lastFragmentShowed)
{//As your last fragment was a support type you need to clear your supportFragmentManager
android.support.v4.app.Fragment fr_v4 = getSupportFragmentManager().findFragmentByTag(lastFragmentTag);
getSupportFragmentManager().beginTransaction().remove(fr_v4).commit();
}
fragment = new Fragment_Login();
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.container, fragment,TAG1)
.commit();
lastFragmentTag = TAG1;
lastFragmentShowed = true;
isLastFragmentSupportType = false;
break;
}
//And so on with the others
You need to check what type (support or not) of fragment you are going to use, and check these variables to see if the last fragment was of a different type. If that is the case clean the other fragmentmanager to "clear" the screen so they wont overlap.
Also use TAGS to identify and retrieve your current fragments so you do not need to have Fragment variables over your code.
Finally use onSavedInstanceState so as to keep these values in case you need them.
Hope it helps :)
This answer is inspired from answer by zozelfelfo.
Use these two methods to replace fragments instead of getFragmentManager.beginTransaction.replace...
private void replaceFragment(Fragment fragment, String fragmentTag) {
if(lastFragmentShowed && isLastFragmentSupportType) {
android.support.v4.app.Fragment fr_v4 = getSupportFragmentManager().findFragmentByTag(lastFragmentTag);
getSupportFragmentManager().beginTransaction().remove(fr_v4).commit();
}
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment, fragmentTag)
.commit();
lastFragmentTag = fragmentTag;
lastFragmentShowed = true;
isLastFragmentSupportType = false;
}
private void replaceFragment(android.support.v4.app.Fragment fragment, String fragmentTag) {
if(lastFragmentShowed && !isLastFragmentSupportType) {
Fragment fr = getFragmentManager().findFragmentByTag(lastFragmentTag);
getFragmentManager().beginTransaction().remove(fr).commit();
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment, fragmentTag)
.commit();
lastFragmentTag = fragmentTag;
lastFragmentShowed = true;
isLastFragmentSupportType = true;
}
I'm using BottomNavigationView as Tab Bar and switching fragments as tabs. All but one fragment are Support Fragments (and last one is PreferenceFragment). I'm using "hide-add-show" rather than "remove-replace". So, status of fragments in other tabs can be preserved.
Original function to switch:
private Fragment lastFragment = null;
private void switchFragment(Fragment fragment) {
if (lastFragment != fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (null != lastFragment) {
transaction.hide(lastFragment);
}
lastFragment = fragment;
if (!fragment.isAdded()) {
transaction.add(R.id.fragment_container, fragment);
}
transaction.show(fragment).commitAllowingStateLoss();
}
}
I don't use tag nor boolean, just want to keep a reference to last fragment object. So, when switching, just call switchFragment() with instance of any fragment:
private Object lastFragment = null;
private void switchFragment(Object fragment) {
if (lastFragment != fragment) {
if (null != lastFragment) {
if (lastFragment instanceof android.support.v4.app.Fragment) {
hideFragment((android.support.v4.app.Fragment) lastFragment);
} else if (lastFragment instanceof android.app.Fragment) {
hideFragment((android.app.Fragment) lastFragment);
}
}
lastFragment = fragment;
if (fragment instanceof android.support.v4.app.Fragment) {
showFragment((android.support.v4.app.Fragment) fragment);
} else if (fragment instanceof android.app.Fragment) {
showFragment((android.app.Fragment) fragment);
}
}
}
So, this function still do the same things but switch between Support Fragment and Native Fragment by checking the target class. Helper functions:
// Support Version:
private void hideFragment(android.support.v4.app.Fragment fragment) {
getSupportFragmentManager().beginTransaction().hide(fragment).commit();
}
private void showFragment(android.support.v4.app.Fragment fragment) {
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (!fragment.isAdded()) {
transaction.add(R.id.fragment_container, fragment);
}
transaction.show(fragment).commitAllowingStateLoss();
}
// Native Version:
private void hideFragment(android.app.Fragment fragment) {
getFragmentManager().beginTransaction().hide(fragment).commit();
}
private void showFragment(android.app.Fragment fragment) {
android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
if (!fragment.isAdded()) {
transaction.add(R.id.fragment_container, fragment);
}
transaction.show(fragment).commitAllowingStateLoss();
}
To avoid confusion, I removed the import so classes require full names.
In my app, I need to remove a set of fragments from transaction when the OS recreate my app due to configuration change. I'm trying to do it as following;
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
FragmentManager fm = getSupportFragmentManager();
List<android.support.v4.app.Fragment> fragments = fm.getFragments();
for (Fragment fragment : fragments) {
if (fragment != null) {
if (!((fragment instanceof FragmentType1) ||
(fragment instanceof FragmentType2) ||
(fragment instanceof FragmentType3))) {
FragmentTransaction trans = fm.beginTransaction();
trans.remove(fragment).commit();
}
}
}
}
}
Though trans.remove(fragment).commit() is executed successfully, but debugging shows that these fragments are still there in FragmentManager. Can anybody tell what I'm doing wrong here.
I have a few fragments in my app, but my code opens a new fragment every time I click the button.
I want to know how can I change this, and make the fragment return to the exact same state I left it in.
The code im using right now:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments);
MainActivity fragment = new MainActivity();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_place, fragment);
transaction.commit();
turnGPSOn();
}
public void onSelectFragment(View view) {
if (view == findViewById(R.id.add))
{
newFragment = new Add();
}
else if (view == findViewById(R.id.map))
{
newFragment = new MainActivity();
}
else
{
newFragment = new Add();
}
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_place, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Thanks!
You are getting a new fragment each time because you are calling to new XXX() each time.
I think you could use findFragmentByTag in order to solve this problem. As you can see here the replace function can accept a third parameter that is a String, this String can be used as an id to identify different fragments you have used previously.
So to sum up you can:
Call Fragment f = getSupportFragmentManager().findFragmentByTag("FragAdd"); for example in order to retrieve the first fragment.
If f is null, that means that you haven't used that fragment yet, so you have to call to new Add() if not, use that fragment to replace the old one. For example like this:
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_place, newFragment, "FragAdd"); //or whatever other string you want to use
transaction.addToBackStack(null);
transaction.commit();
Hope it helps :)
I faced this issue a time ago, and managed to solve it for applications with one visible fragment at a time; for activities with several visible fragments, you'll need to make some adjustments. This is what I did.-
Create a custom ParentActivity, so that all my activities extend it. ParentActivity knows about which is the current Fragment that is showed, and how to show a new one.
public String currentFragmentTag;
public ParentFragment getCurrentFragment(int fragmentWrapperResId) {
ParentFragment res = null;
FragmentManager fragmentManager = getSupportFragmentManager();
res = (ParentFragment) fragmentManager.findFragmentById(fragmentWrapperResId);
if (res != null && res.isHidden()) {
if (currentFragmentTag != null) {
res = (ParentFragment) fragmentManager.findFragmentByTag(currentFragmentTag);
}
}
return res;
}
public void openFragment(ParentFragment fragment, int fragmentWrapperResId, int enterAnim, int exitAnim, int popEnterAnim, int popExitAnim, boolean addToBackStack) {
FragmentManager fragmentManager = getSupportFragmentManager();
ParentFragment currentFragment = getCurrentFragment(fragmentWrapperResId);
if (currentFragment != null && currentFragment.getTagName().equals(fragment.getTagName())) {
return;
}
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim);
if (currentFragment != null) {
transaction.hide(currentFragment);
}
if (fragment.isAdded()) {
transaction.show(fragment);
} else {
transaction.add(fragmentWrapperResId, fragment, fragment.getTagName()).setBreadCrumbShortTitle(fragment.getTagName());
}
if (addToBackStack) {
transaction.addToBackStack(fragment.getTagName());
} else {
currentFragmentTag = fragment.getTagName();
}
transaction.commit();
}
Create a ParentFragment, to be extended by the rest of Fragments, with a tag getter
public String getTagName() {
return getClass().getSimpleName() + System.identityHashCode(this);
}
As you can see, the main idea is not replacing visible fragments, but just adding them and show/hide whenever it's needed. This way, the fragments will keep their states, as they're not destroyed until you remove them from the bakstack.