Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java onbackpressed()从活动到特定片段_Java_Android_Android Fragments_Android Intent - Fatal编程技术网

Java onbackpressed()从活动到特定片段

Java onbackpressed()从活动到特定片段,java,android,android-fragments,android-intent,Java,Android,Android Fragments,Android Intent,我有一个包含3个片段的MainActivity类(每个片段都在自己的类中) 我的第三个片段(LoginFragment)将允许登录一个用户,然后转到一个新的活动(new Intent),为该用户提供一些信息,比如产品 如果我按下返回键,该意图将返回LoginFragment。 我覆盖@OnBackPressed以启动Main活动: Intent intent = new Intent(this, MainActivity.class); startActivity(intent); this.f

我有一个包含3个片段的MainActivity类(每个片段都在自己的类中) 我的第三个片段(LoginFragment)将允许登录一个用户,然后转到一个新的活动(new Intent),为该用户提供一些信息,比如产品

如果我按下返回键,该意图将返回LoginFragment。 我覆盖
@OnBackPressed
以启动Main活动:

Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
this.finish();
我需要知道如何用MainActivity中的LauncherFragment(片段1)替换该片段

我有这个解决方案,但它需要0.5秒到1-2秒(基于设备)

Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
this.finish();

直接转到片段1会很酷,想完成第三个片段,谢谢:)

如果您希望它尽可能快,请使用一个活动和片段来改变内容。添加片段不会创建新窗口,而活动会创建新窗口


还要查看片段/活动启动中的应用程序逻辑(
onCreate()
onResume()
,等等)。这将是主要因素。

我用这个想法解决了这个问题 onBackPressed()我调用了一个新的意图,但使用了附加功能 在包含3个片段onRestart()的MainActivity中,我检查它是否来自这个类(包含额外的内容),然后转到这个片段(单击、替换、删除)

在主要活动中,我得到了这个

@Override
    protected void onRestart() {
        super.onRestart();
        Intent intent = getIntent();
        boolean navigate = intent.getBooleanExtra(Constants.Intents.NAVIGATE_BACK, false);
        if (navigate) {
            View homeView = bottomNavigationView.findViewById(R.id.home);
            homeView.performClick();
            intent.removeExtra(Constants.Intents.NAVIGATE_BACK);
        }
    }

你在真实的设备上测试这段代码吗?@DavidHackro是的,在Nexus 6p和模拟器上测试,如果我理解,标志将重新创建片段,因此这是延迟。如果设备需要1-2秒来创建片段或启动活动,则出现问题。@JeffreyBlattman我的Nexus6p为0.5秒或更快,但这是一个好设备。其他设备(如其他80%的设备)的速度较慢,我在调用重新启动时尝试了我看到的所有想法在MainActivity上,然后转到LoginFragment我正在尝试了解如何转到LauncherFragment如何完成该LoginFragment您不“完成”一个片段。您可以在顶部“添加”一个新片段,您可以用另一个片段“替换”它,或者您可以“删除”该片段。
@Override
    protected void onRestart() {
        super.onRestart();
        Intent intent = getIntent();
        boolean navigate = intent.getBooleanExtra(Constants.Intents.NAVIGATE_BACK, false);
        if (navigate) {
            View homeView = bottomNavigationView.findViewById(R.id.home);
            homeView.performClick();
            intent.removeExtra(Constants.Intents.NAVIGATE_BACK);
        }
    }