I'm using the v7.widget.Toolbar in my app, but I'm getting some funky functionality. I have my main activity and fragments that are placed over it. When there are no fragments on the backStack, the hamburger button shows and the menu works correctly. When I add a fragment to the backStack, the up caret shows correctly, however when I click the up caret, the nav menu opens instead of the fragment being popped off the stack.
Now if there's a real answer, I'll take it, but at this point I will take a hackish solution. I tried adding a listener so I knew when the action bar button was hit, but that just made it so the fragment popped, the page went back, but the nav menu still opened. onOptionsItemSelected is not being called (due to the way I implemented the Drawer Toggle, but doing it the "correct" way gave me way more problems, such as no nav menu showing on the main page at all).
To sum it up for clarity: The up caret is opening the nav menu, instead of going back.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = getTitle();
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
frameLayout = (FrameLayout) findViewById(R.id.frame_layout);
setSupportActionBar(toolbar);
//Listen for changes in the back stack
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerContent = findViewById(R.id.drawer_content);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new DrawerListItemAdapter(DRAWER_ITEMS, getApplicationContext()));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
public void onDrawerClosed(View view) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
Log.d("Main", "Open Menu");
}
};
mDrawerToggle.syncState();
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
ActionBar ab = getSupportActionBar();
if(ab != null){
ab.setDisplayHomeAsUpEnabled(canback);
}
if(!canback){
//App can crash as mDrawerToggle will be null when app launches
try{
mDrawerToggle.syncState();
}catch (Exception e){
e.printStackTrace();
}
}
Log.d("Main", "shouldDisplayHomeUp");
}
#Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
Log.d("Main", "Up carat pressed");
getSupportFragmentManager().popBackStack();
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.d("Main", "Menu item clicked: " + Integer.toString(item.getItemId()));
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
The solution that worked for me
A combination of Alex' answer (including his comment in the answer) below and this hacky answer.
You can use setToolbarNavigationClickListener() - it sets the listener that handles clicks when drawer indicator is disabled
drawerToggle.setToolbarNavigationClickListener((View view) -> {
getSupportFragmentManager().popBackStack();
});
Related
I've been trying to create a navigation drawer for an existing app. I've found a few tutorials for this, but most of them (including the official Android guide) appear to be for the v4 ActionBarDrawerToggle library, which has been deprecated. I'm trying to use the v7 library instead, but my ActionBarDrawerToggle doesn't seem to do what the documentation says it should do.
Edit: Modified my code as per the answer below. The hamburger icon now switches back and forth correctly, but when the user taps the hardware back button to go back to the main fragment of my app, the hamburger icon disappears entirely. Why does this happen?
private void addDrawerItems() {
String[] itemArray = {"About", "Nearby", "Settings", "Feedback",};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("ContributionsActivity", "Item " + position + " selected");
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.title_activity_contributions);
setContentView(R.layout.activity_contributions);
//Set up navigation drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
addDrawerItems();
setupDrawer();
...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// enabling drawer toggle by clicking on the app icon.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
} else {
switch (item.getItemId()) {
case android.R.id.home:
if (mediaDetails.isVisible()) {
getSupportFragmentManager().popBackStack();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
You're missing sync state, add it and everything should be fine.
I'm using NavigationDrawer as the main activity, but when I go to another fragment I want to modify the menu, putting an arrow to back to the home and hide the search icon of the navbar, so I'm having two problems here, I can hide the search icon when I change the fragment, but when I'm back to the navigationMain it should be visible again, which is not happening, and if I am in another fragment the navigation bar must be removed and an arrow back must appear so I can get back to home, this is what I've tried so far:
public class NavigationMain extends ActionBarActivity{
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
static Toolbar toolbar;
TextView toolbartitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_main);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbartitle = (TextView) findViewById(R.id.titletool);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
//getSupportActionBar().setTitle(mTitle);
toolbartitle.setText(mTitle);
getSupportActionBar().setDisplayShowTitleEnabled(false);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
//getSupportActionBar().setTitle(mDrawerTitle);
toolbartitle.setText(mDrawerTitle);
getSupportActionBar().setDisplayShowTitleEnabled(false);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
setSupportActionBar(toolbar);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbartitle.setText("Nav");
toolbar.inflateMenu(R.menu.main);
mDrawerToggle.syncState();
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, toolbartitle.getText());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = new InstituicoesFragment();
switch (position) {
case 0:
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
break;
}
// Load your conten here
Toast.makeText(NavigationMain.this, "Position" + position, Toast.LENGTH_LONG).show();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
//getSupportActionBar().setTitle(mTitle);
toolbartitle.setText(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
In my Fragment I add the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
menu.removeItem(R.id.action_websearch);
super.onCreateOptionsMenu(menu, inflater);
}
i used this method :
i inflate the menu for the actionbar with all the items already in.
then in the Activity onCreateOptionsMenu() i check wich fragment is displayed and i set the visibility of the items accordingly.
then in the onSectionAttached method i call invalidateOptionsMenu(); that will reload the onCreateOptionsMenu so i can have different menu items on each fragment selected
for checking i use boolean flags and if the flag is true it means that the fragment is n view, like:
viewing the first fragment:
ft.replace(R.id.container, firstFragment);
firstfragmentIsOn=true;
secondFragmentIsOn=false;
viewing the second fragment:
ft.replace(R.id.container, secondFragment);
firstfragmentIsOn=false;
secondFragmentIsOn=true;
and in the onCreateOptionsMenu:
MenuItem item1=menu.findItem(R.id.item1);
MenuItem item2=menu.findItem)(R.id.item2);
if(firstfragmentIsOn)
{
item1.setVisible(true);
item2.setVisible(false);
}
if(secondFragmentIsOn)
{
item1.setVisible(false);
item2.setVisible(true);
}
I've been trying to make my Navigation Drawer open using the ActionBarActivity's Up button for a few hours now, but I just can't seem to work it out.
Right now, I can open it by swiping/sliding right and I can see the arrow Up/Back button in the ActionBar, but the Navigation Drawer won't open once I tap the button.
Please note I'm using Support v7 ActionBarDrawerToggle.
Here's my ActionBarActivity's onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new HomeFragment())
.commit();
}
Log.d(TAG, "onCreate");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Log.d(TAG, "onPostCreate");
mDrawerToggle.syncState();
}
Am I missing something? Perhaps there's a method call that links the ActionBar's Up/Back button to the DrawerToggle?
Any help/guidance is very well appreciated.
Update: I also tried using mDrawerToggle.syncState(); and nothing changed. Updated the onCreate method above to include the syncState call.
Update 2: I updated the code again to how it currently stands in my MainActivity file. I made a few changes as suggested but the drawer still won't open.
I've tested this in two devices: in an HTC One m7 with Android 5.0.2 and Sense 6.5 and in an x86 AVD Emulator running Lollipop SDK 21.
Take a look at my codes first:
public class HomeActivity extends ActionBarActivity implements
DrawerCloseListener {
private Toolbar toolbar;
private DrawerLayout drawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.home_toolbar);
toolbar.setNavigationIcon(R.drawable.icon_nav);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.app_name, R.string.app_name);
drawerToggle.setHomeAsUpIndicator(R.drawable.icon_nav);
drawer.setDrawerListener(drawerToggle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (drawer.isDrawerOpen(Gravity.LEFT | Gravity.START)) {
drawer.closeDrawers();
return;
}
super.onBackPressed();
}
#Override
public void onDrawerClose() {
// TODO Auto-generated method stub
if (drawer.isDrawerOpen(Gravity.LEFT | Gravity.START)) {
drawer.closeDrawers();
}
}
}
And among codes above, I replaced ActionBar by ToolBar, but you still can use ActionBar where there is a ToolBar. Did you miss something?
You need to sync your drawer toggle in order to get the up button to well ... sync :)
mDrawerToggle.syncState();
You need to change order of two lines :
1.
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close);
then 2.
mDrawerLayout.setDrawerListener(mDrawerToggle);
Because while setting setDrawerListener the object mDrawerToggle was not initialized
Hope this will solve your work
I think you should add
mDrawerToggle.setDrawerIndicatorEnabled(true);
and move this line mDrawerLayout.setDrawerListener(mDrawerToggle); after mDrawerToggle = new ActionBarDrawerToggle(...);
Edit: After I checked my code again, the closing and opening is handled in separate method
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(drawerList)) {
mDrawerLayout.closeDrawer(drawerList);
}
else {
mDrawerLayout.openDrawer(drawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I've implemented the newest appcompat library and using the Toolbar as action bar. But the problem is I cannot catch the home button / hamburger icon click event. I've tried and looked everything but doesn't seem to find a similar problem.
This is my Activity class :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Set up the drawer.
navDrawerFragment =
(NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
navDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout),
toolbar);
}
And this is my NavigationDrawerFragment class :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
currentSelectedPosition = savedInstanceState.getInt(
STATE_SELECTED_POSITION);
fromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(currentSelectedPosition);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like
// to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
drawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
drawerListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
selectItem(position);
}
});
//mDrawerListView.setAdapter();
//mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return drawerListView;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
fragmentContainerView = getActivity().findViewById(fragmentId);
this.drawerLayout = drawerLayout;
// set a custom shadow that overlays the main
// content when the drawer opens
drawerLayout.setDrawerShadow(
R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view
// with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
drawerToggle = new ActionBarDrawerToggle(
getActivity(),
drawerLayout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// If the user hasn't 'learned' about the drawer,
// open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!userLearnedDrawer && !fromSavedInstanceState) {
drawerLayout.openDrawer(fragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
drawerLayout.post(new Runnable() {
#Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, currentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("cek", "item selected");
if (drawerToggle.onOptionsItemSelected(item)) {
Log.d("cek", "home selected");
return true;
}
return super.onOptionsItemSelected(item);
}
when I clicked a menu item, the log "item selected" gets called. But when I click on the home button, it opens navigation drawer but the log "home selected" never get called. I've set onOptionsItemSelected method inside my Activity as well, but it still doesn't get called.
If you want to know when home is clicked is an AppCompatActivity then you should try it like this:
First tell Android you want to use your Toolbar as your ActionBar:
setSupportActionBar(toolbar);
Then set Home to be displayed via setDisplayShowHomeEnabled like this:
getSupportActionBar().setDisplayShowHomeEnabled(true);
Finally listen for click events on android.R.id.home like usual:
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
Timber.d("Home pressed");
}
return super.onOptionsItemSelected(menuItem);
}
If you want to know when the navigation button is clicked on a Toolbar in a class other than AppCompatActivity you can use these methods to set a navigation icon and listen for click events on it. The navigation icon will appear on the left side of your Toolbar where the the "home" button used to be.
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_nav_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("cek", "home selected");
}
});
If you want to know when the hamburger is clicked and when the drawer opens, you're already listening for these events via onDrawerOpened and onDrawerClosed so you'll want to see if those callbacks fit your requirements.
mActionBarDrawerToggle = mNavigationDrawerFragment.getActionBarDrawerToggle();
mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// event when click home button
}
});
in mycase this code work perfect
This is how I do it to return to the right fragment otherwise if you have several fragments on the same level it would return to the first one if you donĀ“t override the toolbar back button behavior.
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
I think the correct solution with support library 21 is the following
// action_bar is def resource of appcompat;
// if you have not provided your own toolbar I mean
Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar);
if (toolbar != null) {
// change home icon if you wish
toolbar.setLogo(this.getResValues().homeIconDrawable());
toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//catch here title and home icon click
}
});
}
I have handled back and Home button in Navigation Drawer like
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
NavigationView navigationView;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
//showing first fragment on Start
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.content_fragment, new FirstFragment()).commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//listener for home
if(id==android.R.id.home)
{
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Begin the transaction
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (id == R.id.nav_companies_list) {
fragment = new FirstFragment();
// Handle the action
}
// Begin the transaction
if(fragment!=null){
if(item.isChecked()){
if(getSupportFragmentManager().getBackStackEntryCount()==0){
drawer.closeDrawers();
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}
return true;
}
public void removeAllFragments(){
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public void replaceFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.WikiCompany, fragment).addToBackStack("")
.commit();
}
public void updateDrawerIcon() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
drawerToggle.setDrawerIndicatorEnabled(false);
else
drawerToggle.setDrawerIndicatorEnabled(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 50);
}
public void resetActionBar()
{
//display home
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
and In each onViewCreated I call
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((HomeActivity)getActivity()).updateDrawerIcon();
((HomeActivity) getActivity()).setActionBarTitle("List");
}
This is how I implemented it pre-material design and it seems to still work now I've switched to the new Toolbar. In my case I want to log the user in if they attempt to open the side nav while logged out, (and catch the event so the side nav won't open). In your case you could not return true;.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (!isLoggedIn() && item.getItemId() == android.R.id.home) {
login();
return true;
}
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
I changed the DrawerLayout a bit to get the events and be able to consume and event, such as if you want to use the actionToggle as back if you are in detail view:
public class ListenableDrawerLayout extends DrawerLayout {
private OnToggleButtonClickedListener mOnToggleButtonClickedListener;
private boolean mManualCall;
public ListenableDrawerLayout(Context context) {
super(context);
}
public ListenableDrawerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListenableDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Sets the listener for the toggle button
*
* #param mOnToggleButtonClickedListener
*/
public void setOnToggleButtonClickedListener(OnToggleButtonClickedListener mOnToggleButtonClickedListener) {
this.mOnToggleButtonClickedListener = mOnToggleButtonClickedListener;
}
/**
* Opens the navigation drawer manually from code<br>
* <b>NOTE: </b>Use this function instead of the normal openDrawer method
*
* #param drawerView
*/
public void openDrawerManual(View drawerView) {
mManualCall = true;
openDrawer(drawerView);
}
/**
* Closes the navigation drawer manually from code<br>
* <b>NOTE: </b>Use this function instead of the normal closeDrawer method
*
* #param drawerView
*/
public void closeDrawerManual(View drawerView) {
mManualCall = true;
closeDrawer(drawerView);
}
#Override
public void openDrawer(View drawerView) {
// Check for listener and for not manual open
if (!mManualCall && mOnToggleButtonClickedListener != null) {
// Notify the listener and behave on its reaction
if (mOnToggleButtonClickedListener.toggleOpenDrawer()) {
return;
}
}
// Manual call done
mManualCall = false;
// Let the drawer layout to its stuff
super.openDrawer(drawerView);
}
#Override
public void closeDrawer(View drawerView) {
// Check for listener and for not manual close
if (!mManualCall && mOnToggleButtonClickedListener != null) {
// Notify the listener and behave on its reaction
if (mOnToggleButtonClickedListener.toggleCloseDrawer()) {
return;
}
}
// Manual call done
mManualCall = false;
// Let the drawer layout to its stuff
super.closeDrawer(drawerView);
}
/**
* Interface for toggle button callbacks
*/
public static interface OnToggleButtonClickedListener {
/**
* The ActionBarDrawerToggle has been pressed in order to open the drawer
*
* #return true if we want to consume the event, false if we want the normal behaviour
*/
public boolean toggleOpenDrawer();
/**
* The ActionBarDrawerToggle has been pressed in order to close the drawer
*
* #return true if we want to consume the event, false if we want the normal behaviour
*/
public boolean toggleCloseDrawer();
}
}
The easiest approach we could do is change the home icon to a known icon and compare drawables (because android.R.id.home icon can differ to different api versions
so set a toolbar as actionbar
SetSupportActionBar(_toolbar);
_toolbar.NavigationIcon = your_known_drawable_here;
for (int i = 0; i < _toolbar.ChildCount; i++)
{
View v = _toolbar.GetChildAt(i);
if (v is ImageButton)
{
ImageButton imageButton = v as ImageButton;
if (imageButton.Drawable.GetConstantState().Equals(_bookMarkIcon.GetConstantState()))
{
//here v is the widget that contains the home icon you can add your click events here
}
}
}
In my case I had to put the icon using:
toolbar.setNavigationIcon(R.drawable.ic_my_home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
And then listen to click events with default onOptionsItemSelected and android.R.id.home id
For anyone looking for a Xamarin implementation (since events are done differently in C#), I simply created this NavClickHandler class as follows:
public class NavClickHandler : Java.Lang.Object, View.IOnClickListener
{
private Activity mActivity;
public NavClickHandler(Activity activity)
{
this.mActivity = activity;
}
public void OnClick(View v)
{
DrawerLayout drawer = (DrawerLayout)mActivity.FindViewById(Resource.Id.drawer_layout);
if (drawer.IsDrawerOpen(GravityCompat.Start))
{
drawer.CloseDrawer(GravityCompat.Start);
}
else
{
drawer.OpenDrawer(GravityCompat.Start);
}
}
}
Then, assigned a custom hamburger menu button like this:
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetDefaultDisplayHomeAsUpEnabled(false);
this.drawerToggle.DrawerIndicatorEnabled = false;
this.drawerToggle.SetHomeAsUpIndicator(Resource.Drawable.MenuButton);
And finally, assigned the drawer menu toggler a ToolbarNavigationClickListener of the class type I created earlier:
this.drawerToggle.ToolbarNavigationClickListener = new NavClickHandler(this);
And then you've got a custom menu button, with click events handled.
Try this code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
//You can get
}
return super.onOptionsItemSelected(item);
}
Add below code to your onCreate() metod
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
Apart from the answer provided by MrEngineer13, there is also another possible reason why the click event might not have been captured in the onOptionsSelected method. Your DrawerLayout may have overlayed your Toolbar's interface component in the layout XML file. Therefore, whenever you attempt to click the Home button, you're only clicking the DrawerLayout, but not the Home button that's located beneath it.
All you have to do now is rearrange your Toolbar in the corresponding layout XML file so that it is not blocked by any other UI component.
Programmatically, I did attempt to call the bringToFront() method on the toolbar (toolbar.bringToFront()). However, in my app's context, it does not seem to be the solution.
I'm using Navigation Drawer in my application.
When the user clicks on any of the menu item in drawer, it opens a new Activity (not fragment).
Now, I'm using slide_right_in/slide_left_out animation as transition between activities.
The code works, but these animations conflicts with the closing animation of Navigation Drawer, as even before the drawer gets completely closed, the current activity starts sliding out to left & next activity starts sliding in from right.
So, is there any way to start the animation only after drawer is completely closed?
Thank You
You can open Activity with a delay. For example, in such a way Activity will be started after 250ms:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(<filter>);
startActivity(intent);
finish();
}
}, 250);
mDrawerLayout.closeDrawer(mDrawerList);
I did this somehow similiar to Jan.
Select an item
If an item gets clicked, i save its id and close the Drawer:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
clickedItem = menuItem.getItemId();
drawerLayout.closeDrawers();
return true;
}
});
Listen for drawer close
If the Drawer gets closed i listen for it and check if an item has been clicked. If it has i call my method to handle the navigation click.
drawerToggle = new ActionBarDrawerToggle(activity, drawerLayout, R.string.accessibility_open_nav, R.string.accessibility_open_nav)
{
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
if(clickedItem != 0)
{
handleNavigationClick();
}
}
};
drawerLayout.setDrawerListener(drawerToggle);
Handle the click
Here i react to the item click on open intents in this case (simplified). You need to reset the clickedItem here to 0. That is, because if you go back to an activity, open and close the drawer, it would still have the clickedItem number and would handle the click again.
private void handleItemClick()
{
switch (clickedItem)
{
case R.id.item_1:
do_something_1;
break;
case R.id.item_2:
do_something_2;
break;
}
clickedItem = 0;
}
Every answer is so complicated..... It's so easy.
Just add a drawerlistener and do something in onClosed() method:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
when you select a item from navigation drawer you will call this method to close the drawer:
drawer.closeDrawer(GravityCompat.START);
after the above method call just add below lines and do whatever you want:
drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(#NonNull View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(#NonNull View drawerView) {
}
#Override
public void onDrawerClosed(#NonNull View drawerView) {
startActivity(finalIntent);
// Or else do something here....
}
#Override
public void onDrawerStateChanged(int newState) {
}
});
Don't close navigation drawer. It will slide with the old activity. Or call startActivity after drawerLayout.closeDrawer(drawerList);
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
drawerLayout.closeDrawer(drawerList);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
//set animation here
startActivity(intent);
finish();
}
The nikis's answer does not cover all cases. If your Fragment or Activity contains map or CameraView it may costs more time. And differences between simple screen and screen with map too big so it's hard to select a good delay.
The best approach is to send callback to NavigationDrawer from just opened Activity/Fragment in onResume(). Then close drawer in this callback.
I extend all my activities where I want to have a Navigation drawer by DrawerActivity class. Because I had a little animation conflict as well so I start my Activities after Navigation drawer is completely closed. This is implementation which covers all cases:
public class DrawerActivity extends AppCompatActivity {
private String[] mMenuTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mTitle;
private ActionBarDrawerToggle mDrawerToggle;
private Boolean isItemClicked = false;
protected void onCreateDrawer() {
mTitle = getResources().getString(R.string.app_name);
mMenuTitles = new String[]{getString(R.string.drawer_item1), getString(R.string.drawer_item2), getString(R.string.drawer_item3)};
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setScrimColor(getResources().getColor(R.color.black_transparent_30));
// mDrawerLayout.setScrimColor(Color.TRANSPARENT);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mMenuTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
// R.mipmap.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
If item is clicked, I start activity on checked position.
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
if (isItemClicked) {
int position = mDrawerList.getCheckedItemPosition();
startMyActivity(position);
isItemClicked = false;
}
Method setCheckedItem is overriden in extended activities for showing checked item consistently.
setCheckedItem(mDrawerList);
// getSupportActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
// getSupportActionBar().setTitle(mTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setCheckedItem(ListView mDrawerList) {
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setCheckedItem(mDrawerList);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position) {
mDrawerList.setItemChecked(position, true);
// setTitle(mMenuTitles[position]);
// Toast.makeText(this, mTitle, Toast.LENGTH_SHORT).show();
// startMyActivity(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
public void startMyActivity(int position) {
//is overriden in extended activities for being able to send data to another activity
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
Item is clicked so I set my helper atribute to true.
public void onItemClick(AdapterView parent, View view, int position, long id) {
isItemClicked = true;
selectItem(position);
}
}
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}}
I have found a simple way to get rid of id you may try this and its working and tested.
OLD ANSWER:
int id = -1;
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
drawer.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
if (id == R.id.NAV_YOUR_ACTIVITY_ONE) {
Intent activityIntent = new Intent(getApplicationContext(), YOUR_ACTIVITY_ONE.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
}
else if (id == R.id.NAV_YOUR_ACTIVITY_TWO) {
Intent activityIntent = new Intent(getApplicationContext(), YOUR_ACTIVITY_TWO.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
}
//do not forget to set id again to -1 or else it will cause problem
id=-1;
}
#Override
public void onDrawerStateChanged(int newState) {
}
}
}
UPDATE ANSWER:
You can your ActionBarDrawerToggle too for example observe below code.
int id = -1;
//Use this function for click effect be performed on drawer item clicked
public void perfromDrawerNavigation(){
if (id == R.id.NAV_YOUR_ACTIVITY_ONE) {
Intent activityIntent = new Intent(getApplicationContext(), YOUR_ACTIVITY_ONE.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
}
else if (id == R.id.NAV_YOUR_ACTIVITY_TWO) {
Intent activityIntent = new Intent(getApplicationContext(), YOUR_ACTIVITY_TWO.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
}
//do not forget to set id again to -1 or else it will cause problem
id=-1;
}
//you can write this code in onCreate() also
public void initControl(){
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(
getResources().getString(R.string.activity));
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if(id != -1){
perfromDrawerNavigation();
}
}
};
drawer.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
}