Arpan Sarkar
Arpan Sarkar

Reputation: 199

Unable to handle back button in navigation fragment

In my app I am using a navigation drawer to go different fragment. But when I clicked back button it exit from app. I want when back button clicked in any fragment it navigate to home fragment.

drawer_activity.java to navigate different fragment

public boolean onNavigationItemSelected(MenuItem item) {
    Fragment fragment = null;
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.home) {
        toolbar.setTitle("HOME");
        fragment = new HomeFragment();
    } else if (id == R.id.wishlist) {
        toolbar.setTitle("YOUR WISHLIST");
    } else if (id == R.id.order) {
        toolbar.setTitle("YOUR ORDER HISTORY");
    } else if (id == R.id.cart) {
        toolbar.setTitle("YOUR CART");
    } else if (id == R.id.nav_share) {
        toolbar.setTitle("HOME");
    } else if (id == R.id.account) {
        toolbar.setTitle("YOUR ACCOUNT");
    } else if (id == R.id.logout) {
        finish();
        SharedPrefManager.getInstance(getApplicationContext()).logout();
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();

        ft.replace(R.id.content, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
   }

homefragment.java

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_home, container,false);

    //getting the recyclerview from xml
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recylcerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));

    categoryList = new ArrayList<>();


    loadCategory();
    customCategoryList = new CustomCategoryList(getActivity(),categoryList);
    recyclerView.setAdapter(customCategoryList);
    recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
        @Override
        public void onClick(View view, int position) {
            int id = categoryList.get(position).getCategoryid();
            String category = categoryList.get(position).getCategoryname();
            final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
            ID.setCategoryid(id);
            ID.setCategory(category);
            Log.e("categoryid",ID.getCategoryid()+"");
            Fragment fragment = new ProductListFragment();
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction ft = fragmentManager.beginTransaction();

            ft.replace(R.id.content, fragment);
            ft.commit();

        }

        @Override
        public void onLongClick(View view, int position) {

        }
    }));
    return rootView;
   }

In this fragment when one item click from recycler view it navigate to another fragment. From that fragment when I click back button of my phone it exit from app. I want when back button clicked It goes home fragment always and only back button click from home fragment app exit.

productlistFragment.java

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_product_list, container,false);

    gridView = (GridView) rootView.findViewById(R.id.productlist);
    category = (TextView) rootView.findViewById(R.id.category);
    final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
    categoryid = ID.getCategoryid();
    category.setText(ID.getCategory());

    productList = new ArrayList<>();
    loadProduct();

    customProductList = new CustomProductList(getActivity(),productList);
    gridView.setAdapter(customProductList);
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            productid = productList.get(position).getProductid();
            final GlobalVariable Id = (GlobalVariable)getActivity().getApplication();
            Id.setProductid(productid);
            Intent intent = new Intent(getActivity(), ProductView.class);
            startActivity(intent);
        }
    });

    return rootView;
    }

content.xml

<android.support.constraint.ConstraintLayout 
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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".DrawerActivity"
tools:showIn="@layout/app_bar_drawer">

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

</android.support.constraint.ConstraintLayout>

Upvotes: 0

Views: 52

Answers (1)

Vijay Singh Chouhan
Vijay Singh Chouhan

Reputation: 303

Ok!! Just copy this code and paste you will get what yout want.ft.addToBackStack(null); is the key here.

Fragment fragment = new ProductListFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.content, fragment);
ft.commit();

Upvotes: 1

Related Questions