Search code examples
androidandroid-fragmentsandroid-actionbarappcompatactivity

How to up navigate from fragment activity?


Hi I am having trouble while going back to parent activity from fragment activity. I want back arrow at top left corner inside the action bar.

I am able to show it in action bar activity using this code

getSupportActionBar().setDisplayShowHomeEnabled(true);

But I am not able to do it in tabbed activity's fragment.

((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

Please Help me!!


Solution

  • Add this inside onCreate() of your tabbed activity,

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    

    And for navigating back, you need to override following method in your tabbed activity.

    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == android.R.id.home) {
                onBackPressed();
            }
            return super.onOptionsItemSelected(item);
        }
    

    Happy coding.