1. Code to handle onBackPressed in navigation drawer.
private int stackHeight;
private void intializeBackStack() {
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
stackHeight = getSupportFragmentManager().getBackStackEntryCount();
Log.e("StackVal", ": " + stackHeight);
if (stackHeight > 0) {
// if we have something on the stack (doesn't include the current shown fragment)
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
}
}
});
}
@Override
public void onBackPressed() {
Log.e(TAG, "onBackPressed: height: " + stackHeight);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (stackHeight > 0) {
super.onBackPressed();
} else {
if (stackHeight <= 0 & backPressed + TIME_DELAY > System.currentTimeMillis()) {
super.onBackPressed();
} else {
Toast.makeText(MainActivity.this, R.string.press_back_to_exit, Toast.LENGTH_SHORT).show();
backPressed = System.currentTimeMillis();
}
}
}
}
2.Navigation view header in drawer
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
iv_user = navigationView.findViewById(R.id.iv_user);
tv_username = navigationView.findViewById(R.id.tv_username);
String name = new SessionManager(MainActivity.this).getString(Cons.ACCOUNT_NAME);
Picasso.with(MainActivity.this).load(Cons.BASE_URL).placeholder(R.drawable.ic_profile_new)
.error(R.drawable.ic_profile_new).into(iv_user);
3. To change title bar name
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.add_item);
No comments :
Post a Comment