Search code examples
androidandroid-fragmentslifecycleresumefragmentmanager

Android - Show fragment on resume


I currently have a navigation drawer, which has a few fragments (Home, Help, About) in my activity. On startup it opens up Home. The issue i'm having is that when i go to another fragment such as Help and then proceed to put the phone to sleep and subsequently turn on the phone back on it'll always return to Home instead of help.

I'm quite new to lifecycles but was hoping to get some feedback on how to resume from a different fragment.

EDIT: Provided relevant code Update: Realised that this happens because i reinit the views on resume.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initializeUI();
}


private void initializeUI() {


    fragAbout = new About();
    fragHelp = new Help();
    fragHome = new MyViewPager();


    // Adding fragments to activity
    FragmentManager fragmentManager = getSupportFragmentManager();

    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.add(R.id.main_activity_fraglayout, fragHome);

    transaction.commit();

    ...


}

private void addDrawerItems() {

    ...

    DrawerItemAdapter drawerAdapter = new DrawerItemAdapter(this, R.layout.nav_list_row, drawerItems);
    mDrawerList.setAdapter(drawerAdapter);

    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
                case 0:
                    ...
                    newFragOnClick(fragHome, "Home");
                    break;
                case 1:
                    ...
                    newFragOnClick(fragSettings, "Help");
                    break;
                case 2:
                    ...
                    newFragOnClick(fragAbout, "About");
                    break;
                default:
                    break;

            }
        }
    });
}

private void newFragOnClick(Fragment frag, String actionBarTitle){

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();

    transaction.replace(R.id.main_activity_fraglayout, frag);
    transaction.commit();
}

Solution

  • Use sharedpreferences to save the current tab position and in onResume() use it to move to the saved position.