简体   繁体   中英

How to resume recent fragment when application is re opened again

I am working on android application, lets assume i have the following activities in my application: act1, act2 and act3.

Each of the activities above has a fragments so act1 -> frag1, act2 -> frag2 and so on.

When my application is running and i opened frag1 and then i pressed the home button on my phone. i will be directed to the home page of my Phone.

And ethir if i pressed on the launched icon or pressed the back button again the application is resumed/opened act1 instead of frag1.

So my question here, how to make the application opened the recent fragment instead of the activity? frag1 instead of act1.

Thanks, If you want more information such as code example please tell me.

Create Integer Globally

int CurrentFragment=-1;

Whenever you are calling Fragment in your Activity set a value for Integer Like below, Value should be unique for every fragment.

Fragment fragment1=new FirstFragment()
CurrentFragment=0;
  ft.replace(R.id.content_user_home, fragment1, fragment.toString());
                ft.addToBackStack(backStateName);
                ft.commit();

If you are calling another fragment call like this

Fragment fragment2=new SecondFragment()
CurrentFragment=1;
  ft.replace(R.id.content_user_home, fragment1, fragment.toString());
                ft.addToBackStack(backStateName);
                ft.commit();

In OnResume Check CurrentFragment Value in Switch case

Switch(CurrentFragment){
case 0:
Fragment fragment1=new FirstFragment()
CurrentFragment=0;
  ft.replace(R.id.content_user_home, fragment1, fragment.toString());
                ft.addToBackStack(backStateName);
                ft.commit();
break;

case 1:
Fragment fragment2=new SecondFragment()
CurrentFragment=1;
  ft.replace(R.id.content_user_home, fragment1, fragment.toString());
                ft.addToBackStack(backStateName);
                ft.commit();
break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM