How to change Back Button function in Android (Fragment) - android

I'm developing an android application, I have a problem with the changing of back button function. How i can "replace" the default action of this button ?
I would realize a simple function that allow the user to return to the previous fragment when back button is pressed, for example :
[Main Fragment] ----> [2nd Fragment]
[2nd Fragment] <---- [Main Fragment]
I have read some question like this, but i don't understand how to solve my problem.
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment(getApplicationContext());
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
This is the part of my code where i call the "new fragment".
When i start up my application a new fragment is created (HomeFragment), in this frag i create a new fragment (Fragment_Detail).
What that i want is return from Fragment_Detail to HomeFragment.
I hope I was explanatory

Just add the addToBackStack(null). It will automatically go to the previous fragment loaded in stack.
HomeFragment fragment = new HomeFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.content, fragment,TAG)
.commit();
Refer addToBackStack() and refer this answer.
Refer the docs

You should take a look at the example: http://developer.android.com/training/implementing-navigation/temporal.html#back-fragments

Related

replace current fragment with new one

in my app i need to switch between fragments when different items on the navigation drawer are clicked. I created a new method DisplayFragment for it. Here is the code:
private void DisplayFragment(int position)
{
Fragment fragment = null;
switch (position){
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
case 3:
fragment = new Fragment4();
break;
if(fragment!= null)
this.getFragmentManager().beginTransaction().replace(R.id.frame_container,fragment()).commit();
}
it shows an error for "fragment element in above line as follows " wrong second argument type found android.support.v4.app.Fragment; required android.app.Fragment;"
i tried changing the import from android.support.v4.app.Fragment to android.app.Fragment; but it then shows an error for Fragment fragment = null statement. what am i doing wrong?
You need to get the support fragment manager to use android.support.v4.app.Fragment.
this.getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment).commit();
so, getSupportFragmentManager() instead of getFragmentManager(). Also, you don't need to use this in this case.

Saving state of fragment in navigation drawer

i am using navigation drawer in my android app..
Each of fragment contains async task which getting data from internet and displaying in custom list.
Here is code for selecting fragment:
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
String TAG=null;
switch (position) {
case 0:
fragment = new HomeFragment();
TAG=new String("Home");
break;
case 1:
// fragment = new BlogsFragment();
fragment = new BlogsFragment();
break;
case 2:
// fragment = new NewsFragment();
fragment = new NewsFragment();
break;
case 3:
fragment = new TransferFragment();
break;
case 4:
fragment = new FixturesFragment();
break;
case 5:
fragment = new FeedFragment();
break;
case 6:
// fragment = new TwitterFragment();
fragment = new TwitterFragment();
break;
case 7:
// fragment = new FacebookFragment();
fragment = new FacebookFragment();
break;
case 8:
// fragment = new BookmarkFragment();
fragment = new BookmarkFragment();
break;
default:
break;
}
if (fragment != null) {
ft.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
But when i am switching between fragments an async task started loading data again..
So how to save state of fragment
I tried all the possible solution on stackoverflow
please help me
You can only save the state when your configuration changes or any other conditions. In your case each time you are loading the new fragment due to which it again resumes its life-cycle.
Check this
I think you need to cache/store the server response (async task result) for every visited fragment. If its JSON you could store it as string in SharedPrefs and then just take it back from there. This also assumes some expiration time for cashed responses to refresh it.
Since you do
ft.replace(R.id.frame_container, fragment).commit();
you destroy previously shown fragment completely. You could also play with addToBackStack() instead of replace or with retainInstance state.

Fragment removes when Orientation changes

I am using fragment in my application. When I change the orientation the fragment removes and my main activity gets visible from which I have added this fragment. below is the code -
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ManageDataFragment();
break;
case 1:
fragment = new DownloadFragment();
break;
case 2:
fragment = new UserInfoFragment();
break;
case 3:
fragment = new AboutAppFragment();
break;
case 4:
fragment = new ShareAppFragment();
break;
case 5:
fragment = new SettingsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
I am using this fragment from navigationDrawer like in Gmail application.
What should I do that my fragment remains even I change the orientation of device?
Thanks in Advance
I don't think the accepted answer is the correct so I'm writing this one:
When replacing the fragment you should use the method replace with three arguments so you can find your fragment later:
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment, TAG_FRAGMENT).commit();
Where TAG_FRAGMENT is some string tag.
Then in onCreate if the activity was restarted you can find your fragment and add it to the container:
if(savedInstanceState != null) {
fragment = getFragmentManager().findFragmentByTag(TAG_FRAGMENT);
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment, TAG_FRAGMENT).commit();
}
I had exactly the same problem as mentioned above and I fixed it in the AndroidManifest by adding this:
<activity
...
android:configChanges="orientation|screenLayout|screenSize|layoutDirection">
Hope this helps!
Probably should save position using onSaveInstanceState() and test the bundle argument to onCreate().

Save the state of navigation drawer fragments

I am trying to save the state on the navigation drawer fragments as I toggle between different fragments within the navigation drawer. For Example: I start at Fragment A fire some events, then toggle to Fragment B. Then I want to see the same state of Fragment A when I toggle back to Fragment A from Fragment B.
I tried using the onSavedInstanceState(Bundle savedInstanceState) but it only gets called when the orientation changes in the fragment life cycle. A new fragment gets created whenever I toggle to a new fragment and I can't figure out how to save data from a fragment and reload it on another visit.
I don't want to use backstack() either because it removes all the fragments up to the fragment that I want to restore.
Below is how I call the fragments on the drawer toggle.
private void selectItem(int position) {
Fragment fragment;
String TAG;
switch (position) {
case 0:
fragment = new FragmntA();
TAG = "A";
break;
case 1:
fragment = new FragmentB();
TAG = "B";
break;
case 2:
fragment = new FragmentC();
TAG = "C";
break;
case 3:
fragment = new FragmentD();
TAG = "D";
break;
case 4:
fragment = new FragmentE();
TAG = "E";
break;
default:
fragment = new FragmentA();
TAG = "A";
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment, TAG);
ft.commit()
I don't know if there is any point in the fragment life cycle where I can save its state. Any help would be appreciated. Thanks.
To not loose the state of your fragments when switching from one to another you should do "new Fragment()" only once, and keep the instance in a global variable.
But this will not fix the rotation problem.
For the rotation problem, you should read this => http://blog.sqisland.com/2014/06/navigationdrawer-creates-fragment-twice.html
Not easy but I haven't found another way yet.
define fragment object as static in the class and in newInstance method only initialise is fragment is null otherwise just return the fragment.
This will solve your problem.
but for orientation change you will have to use on saveinstancestate method.

Replace Activity to Fragment

I have a drawer navigation with:
private void DisplayView (int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
       ...  
From an activity I can throw that fragment (fragment2 for example)? With BeginTransaction?
Thanks
A Fragment cannot exist in it's own, eg. without an Activity. It cannot be fired up with an Intent like Activities do. You have to either create a new Activity to hold your new Fragment or replace the Fragment of your current Activity with the new one.
You cannot start fragment as an activity, they need to be added to activities.
Read more in the docs here
Also, see this

Categories

Resources