简体   繁体   English

onbackpressed()从活动到特定片段

[英]onbackpressed() from Activity to Specific Fragment

I have a MainActivity class with 3 Fragments (each in their own class) My third fragment (LoginFragment) will allow Login a user and then go to a new activity (new Intent) with some info for that user like the product. 我有一个带有3个片段的MainActivity类(每个片段都在自己的类中)我的第三个片段(LoginFragment)将允许登录用户,然后转到带有该用户的一些信息(如产品)的新活动(新Intent)。

If I press back on that Intent will go back to the LoginFragment. 如果我按回该Intent,将返回到LoginFragment。 I override the @OnBackPressed to start the MainActivity: 我重写@OnBackPressed以启动MainActivity:

Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
this.finish();

I need to know how to replace that Fragment with the LauncherFragment (Fragment 1) in MainActivity. 我需要知道如何在MainActivity中用LauncherFragment(片段1)替换该片段。

I have this solution but it takes 0.5 sec to 1-2 sec based on device 我有此解决方案,但基于设备需要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();

would be cool to go direct to Fragment 1 like to finish the third fragment thanks :) 直接进入片段1很酷,就像完成第三个片段一样:)

I fixed the issue in this idea onBackPressed() I call a new Intent but with extras In the MainActivity that has the 3 fragments onRestart() I check if it coming from this class ( has that extras ) than go to this fragment (click,replace,delete) 我解决了这个问题,在onBackPressed()这个问题上,我调用了一个新的Intent,但有其他功能 。在MainActivity中,它具有3个片段onRestart(),我检查它是否来自此类(具有该功能)而不是转到该片段(单击,替换,删除)

@Override
    public void onBackPressed() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(Constants.Intents.NAVIGATE_BACK, true);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        this.finish();

}

on the MainActivity I got this 在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);
        }
    }

If you want it to be as fast as possible, use one activity and fragments to vary the contents. 如果您希望它尽可能快,请使用一项活动和片段来更改内容。 Adding a fragment doesn't create a new window, whereas an activity does. 添加片段不会创建新窗口,而活动却可以。

Also look at your application logic in fragment / activity startup ( onCreate() , onResume() , etc). 还要查看片段/活动启动中的应用程序逻辑( onCreate()onResume()等)。 That's going to be the main factor. 这将是主要因素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM