How to implement android Toolbar Back button
Asked Answered
C

6

20

I am using a custom toolbar. I need to add back button to it. Now I am using this code to add the back button.

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        toolbar.setBackgroundColor(getResources().getColor(R.color.white));
        toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

This works fine. I can see the back button added. But consider the case where I am in Fragment1 which has no back button. Now I move to Fragment2 and I add in Back Button. From Fragment 2 I open Fragment 3 and I add the back button again.

Now when I press back button from fragment3 to go back to fragment2 i have to check the Fragment Stack to see whether the back button is required in fragment 2 or not.

Is there any other way to handle back button automatically as we push fragments to stack?

Coastline answered 19/5, 2016 at 14:58 Comment(1)
Can you make me more clear what you exactly want?Defiance
K
0

You can handle back icon very easily. If all of your fragment are in single Activity I really recommend to handle this with following way :

first crate a abstract BaseFragment class which implement FragmentManager .OnBackStackChangedListener then put following method inside that :

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mainActivity = (MainActivity) getActivity();

        getFragmentManager().addOnBackStackChangedListener(this);

        shouldDisplayHomeUp();
    }

    @Override
    public void onBackStackChanged() {
        shouldDisplayHomeUp();
    }


    public boolean shouldDisplayHomeUp() {
        //Enable Up button only  if there are entries in the back stack
        boolean canBack = false;
        try {
            canBack = getFragmentManager().getBackStackEntryCount() > 0;
        } catch (Exception ex) {
//            Log.e(getClass().getCanonicalName(), ex.getMessage());getMessage
        }

        if (canBack) {
            mainActivity.drawerDisable();
        } else {
            mainActivity.drawerEnable();
        }
        return canBack;
    }

By this way disableDrawer & enableDrawer function handle your Icon and OnBackPressed method handle your BackStack Now in your activity when you press back-icon display if needed. your onBackPressed should be something like this :

 int backStackCount = getSupportFragmentManager().getBackStackEntryCount();

            if (backStackCount == 0) {
                //nothing exist in backStack OS handle it
                super.onBackPressed();
            } else {

                getSupportFragmentManager().popBackStack();
}

See full implementation here.

Katharynkathe answered 19/5, 2016 at 15:27 Comment(2)
Thanks for your answer. Do you know why the onBackStackChanged is called multiple times when a fragment is removed from stack?Coastline
I think it's due to BackStack push/pop But I'm not sure.Katharynkathe
D
23

Just add two new line of code. Something like this

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setBackgroundColor(getResources().getColor(R.color.white));
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));

setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onBackPressed();
    }
});
Defiance answered 19/5, 2016 at 15:25 Comment(0)
G
9

This assumes you are using an AppCompatActivity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
        setSupportActionBar(toolbar);

        // enabling action bar app icon and behaving it as toggle button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
   }

Then in the onOptionsItemSelected you can override the home button as follows:

 @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;
        }
        else if(id == android.R.id.home){
            Intent i= new Intent(this, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
Godspeed answered 19/5, 2016 at 15:15 Comment(1)
Why do you need onOptionsItemSelected for Toolbar?Outreach
K
0

You can handle back icon very easily. If all of your fragment are in single Activity I really recommend to handle this with following way :

first crate a abstract BaseFragment class which implement FragmentManager .OnBackStackChangedListener then put following method inside that :

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mainActivity = (MainActivity) getActivity();

        getFragmentManager().addOnBackStackChangedListener(this);

        shouldDisplayHomeUp();
    }

    @Override
    public void onBackStackChanged() {
        shouldDisplayHomeUp();
    }


    public boolean shouldDisplayHomeUp() {
        //Enable Up button only  if there are entries in the back stack
        boolean canBack = false;
        try {
            canBack = getFragmentManager().getBackStackEntryCount() > 0;
        } catch (Exception ex) {
//            Log.e(getClass().getCanonicalName(), ex.getMessage());getMessage
        }

        if (canBack) {
            mainActivity.drawerDisable();
        } else {
            mainActivity.drawerEnable();
        }
        return canBack;
    }

By this way disableDrawer & enableDrawer function handle your Icon and OnBackPressed method handle your BackStack Now in your activity when you press back-icon display if needed. your onBackPressed should be something like this :

 int backStackCount = getSupportFragmentManager().getBackStackEntryCount();

            if (backStackCount == 0) {
                //nothing exist in backStack OS handle it
                super.onBackPressed();
            } else {

                getSupportFragmentManager().popBackStack();
}

See full implementation here.

Katharynkathe answered 19/5, 2016 at 15:27 Comment(2)
Thanks for your answer. Do you know why the onBackStackChanged is called multiple times when a fragment is removed from stack?Coastline
I think it's due to BackStack push/pop But I'm not sure.Katharynkathe
A
0

use Method in Class your Activity

private void setupToolbar(){
  Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);
       ActionBar actionBar=getSupportActionBar();
       actionBar.setDisplayHomeAsUpEnabled(true);
       actionBar.setDisplayShowHomeEnabled(true);
       toolbar.setNavigationOnClickListener(new View.OnClickListener() {
   @Override
          public void onClick(View v) {  
           finish();  
             }
               });
              }
Annuity answered 25/10, 2017 at 8:55 Comment(1)
While the answer could be only of code, it's better to explain a little what you've done, this adds value to your answer also in the futureHiphuggers
E
0

It's works on back pressed function to toolbar

private setUpToolBar() {

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

getSupportActionBar().setDisplayShowHomeEnabled(true);

toolbar.setNavigationOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

onBackPressed();

}

});

}
Ethnomusicology answered 12/12, 2017 at 6:13 Comment(1)
Please edit your code properly and add some explanation.Unchurch
M
0

i have Main activity and Four fragments. In MainActivity i write this code

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();

        }
    });

this is working fine and if you have fragments then create a onBackPressed() method

@Override
public void onBackPressed() {
    int position = mViewPager.getCurrentItem();
    if(position == 2) { // go back to search / result tab from info detail tab
        mViewPager.setCurrentItem(2);
    } else if(position == 0) { // switch from result to search tab or go back to home tab
        SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
        Fragment fragment = sectionsPagerAdapter.getItem(position);
        if(fragment instanceof ResultFragment) {
            Bundle bundle = ((ResultFragment) fragment).getArguments();
            if(bundle != null) {
                sectionsPagerAdapter.replaceFragment(SearchFragment.newInstance(bundle.getString(GlobalInfo.TAG_ID), bundle.getString(GlobalInfo.PART_NO), bundle.getString(GlobalInfo.SERIAL_NO), bundle.getString(GlobalInfo.PART_NAME)), getString(R.string.search), 0);
            }
        } else {
            mViewPager.setCurrentItem(1);
        }
    }
    else if(position == 3){
        SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
        Fragment fragment = new ToolMgtFragment();
        sectionsPagerAdapter.replaceFragment(fragment,"Tool Mgt", 3);
    }
    else {
        super.onBackPressed();
    }
}
Mobile answered 1/2, 2019 at 6:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.