I want to make on my MainActivity a property navigation for my users with hamburger and back arrow.
When I have only one fragment set hamburger, but if i have more fragments added on my MainActivity, set the back arrow.
How do I implement that?
Here is my implementation...
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar toolbar;
private DrawerLayout drawer;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setSupportActionBar(toolbar);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
//TODO: Insert back arrow button if have more than one fragment on backstack
/*getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
int stackHeight = getSupportFragmentManager().getBackStackEntryCount();
if (stackHeight > 0) {
if (getSupportActionBar() != null) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.setDrawerIndicatorEnabled(false);
}
} else {
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.setDrawerIndicatorEnabled(true);
}
}
}
});*/
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), new ListVeiculoFragment(), R.id.container_main);
}
}
Work by creating Interface class:
public interface HideShowIconInterface{
void showHamburgerIcon();
void showBackIcon();
}
Implement Interface in your Activity:
public class YourActivity extends AppCompatActivity implements HideShowIconInterface{
#Override
public void showHamburgerIcon() {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mActionBarDrawerToggle.setDrawerIndicatorEnabled(true);
}
#Override
public void showBackIcon() {
mActionBarDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
In your Fragment, call whatever you want by:
((HideShowIconInterface) getActivity()).showHamburgerIcon();
or
((HideShowIconInterface) getActivity()).showBackIcon();
You have to catch the moment when the numbers of the fragments change and use this code to hide (false) / show (true) the DrawerToggle "Hamburger"
mDrawerToggle.setDrawerIndicatorEnabled(false);
EDIT:
In your Activity (somewhere) you have something like this (where you change current Fragment):
private void selectItem(int position) {
Fragment fragment = new MyFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
I would change last line by this:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();
and then check:
if(fragmentManager.getBackStackEntryCount() > 1) mDrawerToggle.setDrawerIndicatorEnabled(false);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(getResources().getColor(R.color.colorWhite));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
put this code in your activity where you use humbarger style navigation it work for me.
Actually none of above solutions works fully.
There are couple of issues that have to be considered -
a) if using ActionBarDrawerToggle then getSupportActionBar().setDisplayHomeAsUpEnabled is now working as expected - it actually replaces icon for toggle, but clicks are still handled by toggle plus hamburger icon is hidden when toggle is enabled again
b) As fragments transaction (add, restore form backstack) are done asynchronously, check for actual backstack size has to be done after fragment transaction is done - e.g. from fragments onCreateView
Here is code that works for me (in Kotlin):
override fun onCreate(savedInstanceState: Bundle?) {
// ....
drawerToggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(drawerToggle)
drawerToggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white)
drawerToggle.syncState()
drawerToggle.setToolbarNavigationClickListener {
// whatever action is needed on homeAsUp click
onBackPressed()
}
//And this method should be called from fragment's onCreateView
fun showUpNavigation() {
drawerToggle.isDrawerIndicatorEnabled=supportFragmentManager.getBackStackEntryCount() <= 1
}
You just add
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
For more details see Android - Switch ActionBar Back Button to Navigation Button.
Related
I am calling fragments from Main_activity.java and also calling fragments from other fragments but i want to show backspace(<-) arrow button when any fragment is loaded(either from Main_activity or any other fragments) instead of ActionBarDrawerToggle. how can I achieve this?
Main Activity code
public class MainActivity extends AppCompatActivity {
NavigationView nav;
ActionBarDrawerToggle toggle;
DrawerLayout drawerLayout;
Toolbar toolbar;
ImageView homeInToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
nav=findViewById(R.id.navigationview);
drawerLayout=findViewById(R.id.drawer);
// homeInToolbar=findViewById(R.id.homeInToolbar);
toggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
FragmentManager manager=getSupportFragmentManager();
nav.setCheckedItem(R.id.menu_home);
FragmentTransaction transaction=manager.beginTransaction();
manager.beginTransaction().replace(R.id.framelayout,new HomeFragment()).commit();}
Main_Activity where the toogle is shown and after click on students, the image should look like
Add these 2 lines after setSupportActionBar(toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
This works for me.
In main_activity from where I calling the fragment, I have disabled toggle as shown in below code.
public void onClick(View v) {
toggle.setHomeAsUpIndicator(R.drawable.ic_back);
toggle.setDrawerIndicatorEnabled(false);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.framelayout,new FeeFragment(toggle)).addToBackStack(null).commit();
}
});
and where ever necessary, I can enable toggle by below code.
toggle.setDrawerIndicatorEnabled(true);
I have MainActivity which is holding 2 fragments. First fragment has navigation drawer, the second fragment not. In the MainActivity i want to override onBackPressed() method so when the navigation drawer is opened, it has to close the fragment. But i don't know how to get fragment's navigation drawer's state from Activity. Here's the code :
MainActivity.java
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
FragmentListProduct.java
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.fragment_list_product_layout, container, false);
Toolbar toolbar = (Toolbar) mainView.findViewById(R.id.toolbar);
fragmentActivity.setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) mainView.findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(fragmentActivity, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
navigationView = (NavigationView) mainView.findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_cat_all);
}
Of course it gives me error Cannot resolve symbol darwerlayout.
Before i made drawerLayout as a static field, but i got warning Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run). So how to solve this problem, or maybe you have another solution :D
You can access the fragment using the tag, which you'll have to assign when invoking the fragment, like this:
getFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment, "the_tag_here")
.commit();
Access it using getFragmentManager().findFragmentByTag("the_tag")
#Override
public void onBackPressed() {
FragmentListProduct fragment = (FragmentListProduct) getFragmentManager().findFragmentByTag("the_tag_here");
if (fragment != null) {
DrawerLayout drawerLayout = fragment.drawerLayout;
//make drawerLayout public in the fragment
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
Solution 1:
Put your navigation drawer in your main activity.
open the second fragment in the new activity if you do not want navigation drawer there.
Solution 2:
Create a method in your fragment say checkNavigationDrawer().
Get a fragment reference in your activity like this
Fragment yourFragment = (YourFragment)getSupportFragmentManager().findFragmentById(R.id.containerId);
In your onBackPressed () call yourFragment.checkNavigationDrawer(); like this
#Override
public void onBackPressed() {
yourFragment.checkNavigationDrawer();
super.onBackPressed();
}
In your checkNavigationDrawer method check if the navigation drawer is open or not if it is open close it.
public void checkNavigationDrawer(){
if(drawerLayout.isOpen()){
drawerLayout.closeDrawers();
}
}
Hold your FragmentListProduct object in your MainActivity.
Create one method called isDrawerOpen() in the FragmentListProduct fragment.
Now you can call the isDrawerOpen() from MainActivity by using the FragmentListProduct class object.
Go for it!
I'm scratching my head with this one now.... I have an ActionBarActivity that loads an initial Fragment - the original menu is inflated within the activity. Now, I have a navigation bar that, when an item is selected, loads a different fragment and adds this to the backstack.
When I do this, there are a couple of things I want to set:
Set the home as up indicator
Invalidate the options menu from the main activity
Set has options to true for the Fragment
Ensure that the up indicator correctly navigates back to the original Fragment
Something rather strange is going on - the up indicator appears once only and does not behave as the back button and although I've invalidated and inflated a new menu, the new menu gets appended to the original Activity menu.
EDIT: Ok I've resolved the appending issue - forgot to add menu.clear() in the onCreateOptionsMenu method.
My navigation drawer layout has onClick methods to all menu items which would trigger the load of another Fragment:
public void navItemClick(View view) {
switch (view.getId()) {
case R.id.ripSMS:
mNavigationDrawer.toggleHome(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
FragmentTransaction mTrans = getSupportFragmentManager().beginTransaction();
mTrans.replace(R.id.voiceover_frame_layout,new MessageFragment(),"main_ui")
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).addToBackStack("msg").commit();
break;
case R.id.ripEmail:
break;
case R.id.ripSettings:
break;
}
mNavigationDrawer.closeDrawer();
}
toggleHome:
public void toggleHome(boolean show) {
mDrawerToggle.setDrawerIndicatorEnabled(show);
if (!show) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
Once the item is triggered the onCreate contains the invalidate and the hasOptions code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().invalidateOptionsMenu();
setHasOptionsMenu(true);
}
The onCreateOptionsMenu then inflates another menu layout (contains a single item called settings).
As mentioned, this only partially works once - the first time I use the item to load the Fragment, I get the back icon but it's also not working (this is set within onOptionsItemSelected to check for the home item press - it does nothing). When I press the back button it takes me back to the correct place. If I navigate back however, the back arrow now longer shows even though the code runs through onCreate!
Ok so I managed to solve this after some trial and error. Two changes made:
Implement addOnBackStackChangedListener
ActionBarDrawerToggle's setToolbarNavigationClickListener needed to be set
As I only have one activity (everything else is Fragment classes) I added the backstack listener to the Parent Activity's onCreate method:
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
}
});
This resolved the disappearing back arrow when going back to the fragment. Finally added the listener to my NavigationDrawer's setup class:
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
I suppose the only questions I have is everything pointed towards using the onOptionsItemSelected method with android.R.id.home but this never worked for me. It might be the way I've implemented things of course but if someone sees anything obvious as to why please do let me know!
These steps helps you to show back button in toolbar when a fragment is loaded. And to pop out when its clicked.
Set setNavigationOnClickListener to toolbar in you activity.
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportFragmentManager().popBackStack();
}else {
drawer.openDrawer(GravityCompat.START);
}
}
});
Implement FragmentManager.OnBackStackChangedListener in you Activity. And register it with SupportFragmentManager in OnCreate()
getSupportFragmentManager().addOnBackStackChangedListener(this);
OnBackStackChangedListener Implementation method:
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
}
}
For me the above answer was not enough, but i've used #Hamz4h_ and added some more after digging into the ActionBarDrawerToggle class. I'm just calling this method of mine from the activity's onCreate:
private void initNavigationElements() {
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mBinding.drawerLayout, mBinding.appBarMain.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mBinding.drawerLayout.addDrawerListener(toggle);
// Tricking the toggle by giving it its own arrow as a custom indicator.
// It will use it when setDrawerIndicatorEnabled is called with false
toggle.setHomeAsUpIndicator(toggle.getDrawerArrowDrawable());
toggle.syncState();
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
DrawerArrowDrawable drawerArrowDrawable = toggle.getDrawerArrowDrawable();
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
// 1 - Display as arrow
drawerArrowDrawable.setProgress(1);
toggle.setDrawerIndicatorEnabled(false);
} else {
// 2 - Display as arrow menu
drawerArrowDrawable.setProgress(0);
toggle.setDrawerIndicatorEnabled(true);
}
}
});
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This is called only when setDrawerIndicatorEnabled is set as false, meaning we are not at the "root" fragment.
getSupportFragmentManager().popBackStackImmediate();
}
});
}
Hope this will help someone :)
I'm having a problem with the Navigation Drawer Icon.
We replaced the default "back caret" to use a different icon and it works fine.
However, if the navigation drawer is already open and the user rotates their device, then the icon reverts back to the default caret and won't go back to the custom one until the navigation drawer is closed and the onCreate() method for the activity is called again (usually by rotating the device).
Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
// set the toolbar as the action bar
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbar.setNavigationIcon(R.drawable.ic_drawer);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new StartFragment())
.commit();
}
//Init the GameLog
GameLog.init(this);
}
/**
* Initializes the DrawerLayout for the particular activity
*/
public static void init(Activity activity) {
mActivity = activity;
mDrawerLayout = (DrawerLayout)activity.findViewById(R.id.drawer_layout);
mRecyclerView = (RecyclerView)activity.findViewById(R.id.left_drawer);
//set adapter
mRecyclerView.setAdapter(mAdapter);
//set layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
//add a divider between elements
mRecyclerView.addItemDecoration(
new HorizontalDividerItemDecoration.Builder(activity)
.color(Color.WHITE)
.build());
Toolbar toolbar = (Toolbar)((ActionBarActivity)activity).getSupportActionBar().getCustomView();
mDrawerToggle = new ActionBarDrawerToggle(activity, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (activity.getActionBar() != null) {
activity.getActionBar().setDisplayHomeAsUpEnabled(true);
activity.getActionBar().setHomeButtonEnabled(true);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
GameLog.getToggle().syncState();
}
Hopefully this makes sense.
Thanks for any help.
Look into calling ActionBarDrawerToggle#syncState.
https://developer.android.com/reference/android/support/v4/app/ActionBarDrawerToggle.html#syncState()
The setup
I have an activity whose contentView is an instance of a DrawerLayout, which has a navigation drawer with a drawer indicator displayed in the action bar. The activity contains a Fragment, let's call it ListFragment, which contains a list of options. When an option is clicked, I replace the ListFragment with a DetailFragment.
At this point, I would like to display an "up" navigation option instead of the navigation drawer indicator. I'm able to display the "up" icon if I disable the drawer indicator by calling mDrawerToggle.setDrawerIndicatorEnabled(false), but this only removes the drawer icon--it does not remove the functionality--that is, when I click the caret, the navigation drawer is still opened.
Additionally, in these subviews, I would like to disable the opening of the drawer by dragging from the edge of the screen. I have tried doing this by calling setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) but it doesn't seem to have disabled this functionality.
I have tried extending the ActionBarDrawerToggle class to prevent opening the drawer when the indicator is clicked--however, all that happens is that the overriding action (the "up" navigation) is performed, but the drawer still opens.
I have also implemented the steps in Switching between Android Navigation Drawer image and Up caret when using fragments . It works insofar as displaying the caret goes, but despite overriding the up button functionality, the menu still opens (the app does navigate back--it just also opens the drawer).
Question
So, long story short: is there any (preferably clean and elegant, but at this point I'll go with hacky) way to achieve these things when my layout root is a DrawerLayout:
Replace the drawer indicator with an "up" caret (tentatively doable via mDrawerToggle.setDrawerIndicatorEnabled(false))
Prevent the drawer from opening when the caret is clicked, and instead override with my own "up" functionality
Prevent the drawer from opening when I drag from the edge of the screen.
Edit
All right, it looks like if I both override ActionBarDrawerToggle AND onOptionsItemSelected, the menu does not open when I click the caret. But it still opens if I drag from the edge. Help!
Short Code
public void setDrawerState(boolean isEnabled) {
if ( isEnabled ) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
drawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_UNLOCKED);
drawerToggle.setDrawerIndicatorEnabled(true);
drawerToggle.syncState();
}
else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerToggle.setDrawerIndicatorEnabled(false);
drawerToggle.syncState();
}
}
This is only part of the solution that I arrived at, but it was quite hard to figure out this bug, so I'm leaving this here for posterity's sake.
This how I was defining the ListView for my navigation drawer:
<ListView
android:id="#+id/listview_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start|bottom"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
Even after calling setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) I was still able to slide the drawer open.
However, after changing the layout_gravity to "start" this problem seems to be resolved.
I was able to reproduce this issue in a sample, navigation-drawer-only app, so it does appear to be a reproducible issue not unique to my situation.
Building on sonida's answer. After calling setDrawerIndicatorEnabled(false), onNavigateUp wasn't being called still. So, I just created a new onClickListener that called it:
public void setDrawerState(boolean isEnabled) {
if ( isEnabled ) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
drawerToggle.setDrawerIndicatorEnabled(true);
drawerToggle.syncState();
}
else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerToggle.setDrawerIndicatorEnabled(false);
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onSupportNavigateUp();
}
});
drawerToggle.syncState();
}
}
also I think
drawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_UNLOCKED);
has been depreciated, but it works fine without it.
You need to disable swipe and disable the actionbar home button:
Use the below code that builds on the code already given to disable swipe
public void setDrawerState(boolean isEnabled) {
if ( isEnabled ) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
mDrawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_UNLOCKED);
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerToggle.syncState();
getActivity().getActionBar().setHomeButtonEnabled(true);
}
else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerToggle.onDrawerStateChanged(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerToggle.syncState();
getActivity().getActionBar().setHomeButtonEnabled(false);
}
}
Building on answer by #sonida And after using the tweaks given by #luca992 and #jai.
I tried above suggested codes But the "up" or "Back" arrow in left side of action bar was just not showing up in my app. But luckily I was able to fix that.
I had to add this extra line of code in setNavigationDrawerState() [Ref: android.support.v7.app.ActionBarDrawerToggle.setHomeAsUpIndicator ]
toggle.setHomeAsUpIndicator(R.drawable.ic_keyboard_backspace_white_24dp);
I downloaded the drawable: ic_keyboard_backspace_white_24dp from Material.io
Here is the complete code:
MainActivity.java -> onCreate()
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Start: Code automatically generated by Android Studio
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
// End: Code automatically generated by Android Studio
// I had to add this listener as the "back" arrow was totally unresponsive
// Thanks to #luca992
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
// Start: Code automatically generated by Android Studio
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// End: Code automatically generated by Android Studio
// More custom code for other stuff
// ...
}
MainActivity.java -> setNavigationDrawerState()
public void setNavigationDrawerState(boolean isEnabled) {
if ( isEnabled ) {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
}
else {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle.setDrawerIndicatorEnabled(false);
// the extra line of code goes here
toggle.setHomeAsUpIndicator(R.drawable.ic_keyboard_backspace_white_24dp);
toggle.syncState();
}
MainActivity.java -> onBackPressed()
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if(getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportFragmentManager().popBackStack();
}else {
super.onBackPressed();
}
}
MainActivity.java -> startFragment() [dummy function for example]
public void startFragment(){
MyFrag myFrag = new MyFrag();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frag_container ,myFrag)
.addToBackStack(null)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
MyFrag.java --> onViewCreated()
#Override
public void onViewCreated (View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
// Say, using an implemented interface Make call to MainActivitiy's setNavigationDrawerState() passing false
// setNavigationDrawerState(false)
// ...
}
MyFrag.java --> onDestroyView()
#Override
public void onDestroyView(){
// Say, using an implemented interface Make call to MainActivitiy's setNavigationDrawerState() passing true
// setNavigationDrawerState(true)
super.onDestroyView();
}