Home » Android » android – Load Fragment before Navigation Drawer closes

android – Load Fragment before Navigation Drawer closes

Posted by: admin June 16, 2020 Leave a comment

Questions:

I have implemented a navigation drawer and I want to load my fragment before the navigation drawer closes. Currently, the fragment loads in parallel with the drawer closing, so if the fragment is heavy the user interface hangs for a bit.

The code I have is:

private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
                 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                 ft.replace(R.id.content_frame, fragmentProfile);
                 ft.commit();
                 drawerLayout.closeDrawer(drawerNaviListView);
        }
    }

How can I change this so that I see my fragment loading (in background) first and when it has finished loading, the navigation drawer closes?

How to&Answers:

My solution was to load fragment AFTER drawer is closed:
actually call loadFragment method inside onDrawerClosed

 public void onDrawerClosed() {

 // assure the request comes from selecting a menu item, not just closing tab
 if (selectedTab ) 
     selectItem(mSelectedFragment);
     selectedTab = false;
 }

Answer:

Try to load after the drawer is closed
Use handler to create a delayed execution. So that there won’t be any hang when the drawer closes

Inside the method onItemClick(), use the below code :

Handler handler = new Handler();

Runnable runnable = new Runnable() {

            @Override
            public void run() {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
             ft.replace(R.id.content_frame, fragmentProfile);
             ft.commit();

            }
        };

        handler.postDelayed(runnable, 500); // here 500 is the delay 

// other way of doing it is

create an AsyncTask and in doInBackground() method start the fragment transaction and close the drawer in onPostExecute()

Answer:

DrawerLayout.DrawerListener can be used to monitor the state and motion of drawer views.
Avoid performing expensive operations such as layout during animation as it can cause
stuttering; try to perform expensive operations during the STATE_IDLE state. Source.

In other words, Android recommends that you wait for your drawer to close before swapping Fragments.