java - 无法处理导航 fragment 中的后退按钮

标签 java android android-fragments

在我的应用程序中,我使用抽屉导航来访问不同的 fragment 。但是当我单击后退按钮时,它会从应用程序退出。我希望当在任何 fragment 中单击后退按钮时,它会导航到主 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;
   }

在此 fragment 中,当从回收器 View 中单击一个项目时,它将导航到另一个 fragment 。从该 fragment 中,当我单击手机的后退按钮时,它会从应用程序退出。我希望当单击后退按钮时它始终返回主 fragment ,并且只有从主 fragment 应用程序退出时单击后退按钮。

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>

最佳答案

好的!!只需复制此代码并粘贴即可得到您想要的内容。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();

关于java - 无法处理导航 fragment 中的后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52678112/

相关文章:

java - 使用数据库创建新对象

android - 防止 EditText 在软键盘的“下一步”按钮单击上获得焦点

android - 在不更新 ListView 的常规(支持) fragment 中使用 AsyncTaskLoader 更新适配器

使用workmanager的Android定期位置更新

android - PhoneGap : Is there a way to stop the keyboard from resizing the view?

java - XML-RPC 错误,org.xmlpull.v1.XmlPullParserException

android - 如何隐藏底部栏导航。当遵循单一 Activity 设计时?

java - fantom 生成的字节码是否与 java 等效字节码一样高效?

java - File.separator 与 File.pathSeparator

java - 在这种情况下,notifyAll 将如何工作?