Home » Android » android – Up Navigation (Action Bar's back arrow) is not working for fragments

android – Up Navigation (Action Bar's back arrow) is not working for fragments

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’ve drawer-layout as a base layout of my activity and I’m replacing two fragments on a frame present inside this drawer-layout. The first fragment is not added in fragment’s back stack. I’m displaying hamburger icon in my activity (I also want the drawer menu in my first fragment). In second fragment I disabled the hamburger icon by mActionBarDrawerToggle.setDrawerIndicatorEnabled(false) and enabled back button using actionBar.setDisplayHomeAsUpEnabled(true).

In first fragments onResume I enabled hamburger icon by mActionBarDrawerToggle.setDrawerIndicatorEnabled(true)` so that when user presses back button (both hardware and action-bar’s up button) from second fragment,user will come back to first fragment and hamburger icon will be enabled. Everything is working fine only I’m not able to go back from second fragments action bar back button. I’m not able to click it.
Below is my code :-

Activity code

if (Utility.isLargeScreen(this))
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    else
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mHiddenGemsApplication = (HiddenGemsApplication) getApplication();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    initViews();

    setSupportActionBar(mToolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    mTextViewActionBarTitle.setText(getString(R.string.app_name));

    mActionBarDrawerToggle = new ActionBarDrawerToggle(HomeActivity.this, mDrawerLayout, mToolbar, R.string.open_drawer, R.string.close_drawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }
    };

    mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);

    mActionBarDrawerToggle.syncState();

    mFragmentManager = getSupportFragmentManager();

    replaceFragment(new CategoryFragment(), getString(R.string.app_name), CategoryFragment.TAG);

 @Override
public void onBackPressed() {

    if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        mDrawerLayout.closeDrawers();
        return;
    }
    super.onBackPressed();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case android.R.id.home:
            if (mFragmentManager.getBackStackEntryCount() > 0) {
                mFragmentManager.popBackStack();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

 public void replaceFragment(Fragment fragment, String actionBarTitle, String tag) {

    if (mFragmentManager == null)
        return;

    FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.content_frame, fragment, tag);
    if (!tag.equals(CategoryFragment.TAG))
        fragmentTransaction.addToBackStack(tag);
    fragmentTransaction.commit();

    setActionBarTitle(actionBarTitle);
}

public void setActionBarTitle(String actionBarTitle) {
    if (!TextUtils.isEmpty(actionBarTitle))
        mTextViewActionBarTitle.setText(actionBarTitle);
}

public void setDrawerIndicatorEnabled(boolean value) {
    if (mActionBarDrawerToggle != null) {
        mActionBarDrawerToggle.setDrawerIndicatorEnabled(value);
    }
}

Activity XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="nirvaniclabs.com.hiddengems.activities.HomeActivity">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <include
        android:id="@+id/toolbarlayout"
        layout="@layout/toolbar_layout" />

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbarlayout" />
</RelativeLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:menu="@menu/navigation_items" />

</android.support.v4.widget.DrawerLayout>

First Fragment : –

 private Button mButtonTemp;
private AppCompatActivity mActivity;
public static String TAG = "CategoryFragment";

public CategoryFragment() {
    // Required empty public constructor
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    if (context instanceof Activity)
        mActivity = (AppCompatActivity) context;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View viewGroup = inflater.inflate(R.layout.fragment_category, container, false);
    initViews(viewGroup);

    mButtonTemp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ((HomeActivity) mActivity).replaceFragment(new TripListFragment(), "Trip Fragment", TripListFragment.TAG);
        }
    });

    return viewGroup;
}

private void initViews(View viewGroup) {
    mButtonTemp = (Button) viewGroup.findViewById(R.id.btn_temp);
}

@Override
public void onResume() {
    super.onResume();
    ((HomeActivity) mActivity).setDrawerIndicatorEnabled(true);
    ((HomeActivity) mActivity).setActionBarTitle(getString(R.string.app_name));
}

Second Fragment

  private AppCompatActivity mActivity;
public static String TAG = "TripListFragment";

public TripListFragment() {
    // Required empty public constructor
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof Activity)
        mActivity = (AppCompatActivity) context;
}

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

    setHasOptionsMenu(true);
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_trip_list, container, false);
}


@Override
public void onResume() {
    super.onResume();
    ((HomeActivity) mActivity).setDrawerIndicatorEnabled(false);
}

Also, when I’m in second fragment I’m able to swipe and see the drawer menu. I don’t want this behaviour, drawer menu should only open in fragment 1.

If any thing is wrong in my code please let me know.

How to&Answers:

Finally got the answer. In my scenario I’m disabling the drawer indicator by mActionBarDrawerToggle.setDrawerIndicatorEnabled(false); and due to this Navigation icon clicks got disabled. To enable this I’ve to add ToolbarNavigationClickListener to ActionBarDrawerToggle which will enable navigation icon clicks.

Below is the my working code :-

mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

Refer this link for more clarification

Answer:

After struggling with the same problem for ages, I eventually managed to get the Up button to work in fragments with this code.
You must have setHasOptionsMenu set up in onCreate() or onCreateView()

setHasOptionsMenu(true);

Then, in onOptionsItemSelected() add this check for the up / home button being pressed to your switch() [or if…] statement:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    x.L();

    switch (item.getItemId()) {
        case android.R.id.home :
            getActivity().onBackPressed();

            break;

        case R.id.mn_exit :
            exitFragment();

            break;

        default :
            break;
    }

    return super.onOptionsItemSelected(item);
}