如何在两个不同活动类的片段之间切换 [英] how to switch between fragments of two different activity class

查看:41
本文介绍了如何在两个不同活动类的片段之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的活动,即A&B.两者都具有 NavigationDrawer ,外观相似,但不同,因为我无法在活动B中获得活动A的抽屉布局ID.

I have two different activities, A & B. Both have NavigationDrawer , look alike, but not are the same, because I could not get the drawer layout ID of activity A in activity B.

两个活动均具有3个片段(共6个).

Both activity has 3 fragments each (total 6).

NavigationDrawer 仅包含活动类A的所有片段.我的问题是,当我处于活动B中并尝试从导航抽屉中打开活动A的一个片段时,会引发错误

The NavigationDrawer contains all fragments of activity class A only. My problem is, when I am in activity B, and try to open one fragment of activity A from navigation drawer, it throws an error

No view found for id 0x7f090047 (com.wlodsgn.bunbunup:id/linear) for fragment FmMenu{b1e537f0 #0 id=0x7f090047}

我该如何实现?

推荐答案

我在第二个活动中创建了一个意图,并使用有关要调用的片段的信息开始了活动A.

I have created an intent inside the second activity and started the activity A with information about the fragment to be called.

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

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

Now, inside activity A, checked the extra and load the right Fragment:

OnCreate(){
...
if (getIntent().getExtras() != null) {
String intentFragment = getIntent().getExtras().getString("frgToLoad");

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

在尝试为intentFragment赋值之前,必须检查intent是否为null.这是因为无论我是否来自活动B,都会调用该行代码,并且如果intent为null,它将引发错误.

One have to check if intent is null or not before I try to assign a value to intentFragment. This is because that line of code is called whether I am coming from activity B or not, and it will throw error if intent is null.

信用: https://stackoverflow.com/a/36064344/3380537

这篇关于如何在两个不同活动类的片段之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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