如何启动活动并显示特定片段 [英] How to launch activity and show specific fragment

查看:60
本文介绍了如何启动活动并显示特定片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MainActivity,其中添加了多个片段,然后将其显示/隐藏.这是因为MainActivity使用NavigationDrawer.单击抽屉中的项目会导致添加不同的片段(如果不存在),或者添加/隐藏.

I have a MainActivity that has several fragments which are added and then shown/hidden. This is because the MainActivity uses a NavigationDrawer. Clicking on items in the drawer causes different fragments to be added (if they do not exist), or shown/hidden if they do.

我的问题是,如何才能通过来自其他活动的意图启动我的MainActivity,同时显示特定片段?

My question is, how can I launch my MainActivity via an intent from a different activity, and at the same time show a specific fragment?

我是否必须将一些额外内容传递给MainActivity,然后根据该数据添加/显示/隐藏相关片段?还有另一种方法吗?

Would I have to pass some extra to my MainActivity and then based on that data, add/show/hide the relevant fragment? Is there another way?

推荐答案

在创建Intent时,可以给它额外的内容来确定要加载的片段.

When you create your Intent, you can give it an extra that determines the fragment to load.

Intent i = new Intent(this, ActivityClass.class);
i.putExtra("frgToLoad", FRAGMENT_A);

// Now start your activity
startActivity(i);

现在,在活动中检查额外内容并加载正确的片段:

Now, inside your activity check the extra and load the right Fragment:

OnCreate(){
    ...

    int intentFragment = getIntent().getExtras().getInt("frgToLoad");

    switch (intentFragment){
        case FRAGMENT_A:
            // Load corresponding fragment
            break;
        case FRAGMENT_B:
            // Load corresponding fragment
            break;
        case FRAGMENT_C:
            // Load corresponding fragment
            break;
    }
}

这篇关于如何启动活动并显示特定片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆