Navigation Drawer lag on Android
You can do It this way to avoid drawer lag, change your onItemClick:
layoutDrawer.closeDrawer(linearDrawer);
setLastPosition(posicao);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
setFragmentList(lastPosition);
}
}, 200);
Edit: prefered way should be setting DrawerListener on DrawerLayout and setting your fragment in onDrawerClosed
like this:
Fragment mFragmentToSet = null;
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_home:
mFragmentToSet = HomeFragment.newInstance();
break;
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override public void onDrawerSlide(View drawerView, float slideOffset) {}
@Override public void onDrawerOpened(View drawerView) {}
@Override public void onDrawerStateChanged(int newState) {}
@Override
public void onDrawerClosed(View drawerView) {
//Set your new fragment here
if (mFragmentToSet != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(FRAGMENT_CONTAINER_ID, mFragmentToSet)
.commit();
mFragmentToSet = null;
}
}
});
I think I have found the best solution for this !
First do your fragment transaction like so :
new Handler().post(new Runnable() {
@Override
public void run() {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container, finalMenuFragment)
.commit();
}
});
I know it looks useless to post a Runnable but this hack avoid lag on the click animation on the drawer especially when you use
android:background="?attr/selectableItemBackground"
for a clickable element.
And then you close the drawer AT THE END OF THE onResume() function of your fragment (in this example it's "finalMenuFragment") like so :
new Handler().post(new Runnable() {
public void run() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
});
Again I know it seems stupid to post a Runnable but it makes the close animation smooth.
This way, the drawer will close as fast as it can if you want smooth animations and if your fragment has not a lot of views in it, it will close faster and still without lag.
I would like some feedback on this if somebody tested this solution, hope it helps !
Rather than do transaction in onClick, why not do it in onDrawerClosed from DrawerLayout.DrawerListener?