在AndroidX FragmentContainerView中处理BackPress for Fragment

如何解决在AndroidX FragmentContainerView中处理BackPress for Fragment

我有一个 MainActivity ,其中实现了一个抽屉和一个片段。现在,我使用下面提到的 ManageFragments 类从堆栈中添加和删除片段。在 Back Press 上添加到以前的片段之后,我能够彼此替换片段,但是无法从堆栈弹出片段。到目前为止,这是我的实现。

这是我要实现的目标:

DrawerItem1-> Frag1-> Frag2-> Frag3-> Frag4

DrawerItem2-> Frag5

DrawerItem3-> Frag6

DrawerItem4-> Frag7

因此,当用户位于frag1中并按Frag5时。用户应该能够返回到frag1。

同样,如果用户导航到frag4,则可以通过后按

导航回frag1

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:showIn="@layout/app_bar_main">

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/mobile_navigation" />
 </androidx.constraintlayout.widget.ConstraintLayout>

我开发了一个通用类,可以在单个片段容器视图中添加和弹出片段,即“ nav_host_fragment”

ManageFragments.java

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import java.util.Objects;

public class ManageFragments {

public static String backStateName;
public static String fragmentTag;
public static FragmentManager manager;
public static boolean fragmentPopped;

public static void replaceFragment(FragmentActivity fragmentActivity,Fragment fragment) {
    backStateName = fragment.getClass().getName();
    fragmentTag = backStateName;
    manager = fragmentActivity.getSupportFragmentManager();
    fragmentPopped = manager.popBackStackImmediate(backStateName,0);

    if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) { //fragment not in back stack,create it.
        FragmentTransaction ft = manager.beginTransaction();
        ft.replace(R.id.nav_host_fragment,fragment,fragmentTag);
        ft.addToBackStack(backStateName);
        ft.commit();
    }
}

public static void popFragment(FragmentActivity fragmentActivity) {
    manager = Objects.requireNonNull(fragmentActivity).getSupportFragmentManager();
    manager.popBackStackImmediate(backStateName,FragmentManager.POP_BACK_STACK_INCLUSIVE);
}

public static void clearFragments(FragmentActivity fragmentActivity) {
    manager = Objects.requireNonNull(fragmentActivity).getSupportFragmentManager();
    for (Fragment fragment : manager.getFragments()) {
        fragmentActivity.getSupportFragmentManager().beginTransaction().remove(fragment).commit();
    }
  }
}  

这是我 MainActivity.java 的实现。

public class MainActivity extends AppCompatActivity {

private AppBarConfiguration mAppBarConfiguration;
private DrawerLayout drawer;
private NavController navController;
private NavHostFragment navHostFragment;
private NavigationView navigationView;
public static Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view,"Replace with your own action",Snackbar.LENGTH_LONG)
                    .setAction("Action",null).show();
        }
    });
    drawer = findViewById(R.id.drawer_layout);
    navigationView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.

    navHostFragment =
            (NavHostFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.nav_host_fragment);
    navController = navHostFragment.getNavController();
    mAppBarConfiguration = new AppBarConfiguration.Builder(
            navController.getGraph())
            .setDrawerLayout(drawer)
            .build();
    NavigationUI.setupActionBarWithNavController(this,navController,mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView,navController);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_category,menu);
    return true;
}

@Override
public boolean onSupportNavigateUp() {
    return NavigationUI.navigateUp(navController,mAppBarConfiguration);
}

@Override
public void onBackPressed() {
   
    }
}

mobile_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
app:startDestination="@+id/nav_home">

<fragment
    android:id="@+id/nav_home"
    android:name="com.drawerapp.fragment.home.HomeFragment"
    android:label="@string/menu_home"
    tools:layout="@layout/fragment_home">
    <action
        android:id="@+id/action_nav_home_to_subCategoryFragment"
        app:destination="@id/subCategoryFragment"
        app:enterAnim="@anim/fragment_fade_enter" />
</fragment>

<fragment
    android:id="@+id/subCategoryFragment"
    android:name="com.drawerapp.fragment.sub_category.SubCategoryFragment"
    android:label="SubCategoryFragment">
    <action
        android:id="@+id/action_subCategoryFragment_to_galleryFragment"
        app:destination="@id/galleryFragment"
        app:enterAnim="@anim/fragment_fade_enter" />
    <action
        android:id="@+id/action_subCategoryFragment_to_nav_home"
        app:destination="@id/nav_home"
        app:exitAnim="@anim/fragment_fade_exit" />
</fragment>

<fragment
    android:id="@+id/galleryFragment"
    android:name="com.drawerapp.fragment.gallery.GalleryFragment"
    android:label="GalleryFragment">
    <action
        android:id="@+id/action_galleryFragment_to_subCategoryFragment"
        app:destination="@id/subCategoryFragment"
        app:exitAnim="@anim/fragment_fade_exit" />
</fragment>

<fragment
    android:id="@+id/nav_fav"
    android:name="com.drawerapp.fragment.favorites.FavoritesFragment"
    android:label="@string/menu_fav"
    tools:layout="@layout/fragment_favorite">
    <action
        android:id="@+id/action_nav_fav_to_nav_home"
        app:destination="@id/nav_home"
        app:exitAnim="@anim/fragment_fade_exit" />
</fragment>

<fragment
    android:id="@+id/nav_feedback"
    android:name="com.drawerapp.fragment.feedback.FeedbackFragment"
    android:label="@string/menu_feedback"
    tools:layout="@layout/fragment_feedback">
    <action
        android:id="@+id/action_nav_feedback_to_nav_fav"
        app:destination="@id/nav_fav"
        app:exitAnim="@anim/fragment_fade_exit" />
</fragment>

<fragment
    android:id="@+id/nav_about_us"
    android:name="com.drawerapp.fragment.about_us.AboutUsFragment"
    android:label="@string/menu_about_us"
    tools:layout="@layout/fragment_about_us">
    <action
        android:id="@+id/action_nav_about_us_to_nav_feedback"
        app:destination="@id/nav_feedback"
        app:exitAnim="@anim/fragment_fade_exit" />
</fragment>

谢谢。

解决方法

您使用的是NavHostFragment,因此您绝对不应该进行任何碎片交易。

您尝试实现的行为正是connect your NavController to a DrawerLayout时的默认行为,因此您应该删除所有代码并遵循文档。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-