Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DrawerLayout's item click - When is the right time to replace fragment?

I'm developing an application which uses the navigation drawer pattern (With DrawerLayout).

Each click on a drawer's item, replaces the fragment in the main container.

However, I'm not sure when is the right time to do the fragment transaction? When the drawer starts closing? Or after it is closed?

In google's documentaion example, you can see that they are doing the transaction right after the item click, and then close the drawer.
As a result, the drawer seems laggy and not smooth, and it looks very bad (It happens in my application too).

In Gmail and Google Drive applications, on the other way, It seems like they are doing the transaction after the drawer closed (Am I Right?).
As a result, the drawer is not laggy and very smooth, BUT it takes about 1 second (the time it takes to the drawer get closed) at least, to see the next fragment.

It seems like there is no way the drawer will be smooth when immediately doing fragment transaction.

What do you think about that?

Thanks in advance!

like image 458
dor506 Avatar asked Jul 05 '13 14:07

dor506


2 Answers

Yup, couldn't agree more, performing a fragment (with view) transaction results in a layout pass which causes janky animations on views being animated, citing DrawerLayout docs:

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.

So please perform your fragment transactions after the drawer is closed or somebody patches the support library to somehow fix that :)

like image 150
eveliotc Avatar answered Sep 21 '22 12:09

eveliotc


Another solution is to create a Handler and post a delayed Runnable after you close the drawer, as shown here: https://stackoverflow.com/a/18483633/769501. The benefit with this approach is that your fragments will be replaced much sooner than they would be if you waited for DrawerListener#onDrawerClosed(), but of course the arbitrary delay doesn't 100% guarantee the drawer animation will be finished in time.

That said, I use a 200ms delay and it works wonderfully.

private class DrawerItemClickListener implements OnItemClickListener {     @Override     public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {         drawerLayout.closeDrawer(drawerList);         new Handler().postDelayed(new Runnable() {             @Override             public void run() {                 switchFragments(position); // your fragment transactions go here             }         }, 200);     } } 
like image 37
Makario Avatar answered Sep 22 '22 12:09

Makario