Невозможно обработать кнопку возврата во фрагменте навигации - PullRequest
0 голосов
/ 06 октября 2018

В моем приложении я использую навигационный ящик, чтобы перейти к другому фрагменту.Но когда я нажал кнопку «Назад», он вышел из приложения.Я хочу, чтобы при нажатии кнопки «Назад» в любом фрагменте он переходил к домашнему фрагменту.

hook_activity.java для навигации по другому фрагменту

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;
   }

В этом фрагменте, когда один элемент щелкает в представлении переработчика, он перемещается к другому фрагменту.Из этого фрагмента, когда я нажимаю кнопку «Назад» на моем телефоне, он выходит из приложения.Я хочу, чтобы при нажатии кнопки «Назад» всегда возвращался фрагмент домой, и только при нажатии кнопки «Назад» при выходе из приложения «Домашний фрагмент».

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>

1 Ответ

0 голосов
/ 06 октября 2018

Хорошо !!Просто скопируйте этот код и вставьте, и вы получите то, что хотите. ft.addToBackStack(null); здесь ключ.

Fragment fragment = new ProductListFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.content, fragment);
ft.commit();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...