android - 如何知道哪个 fragment 称为另一个 fragment ?

标签 android android-fragments

我在 Android 中遇到了这个问题。考虑三个 fragment :ABCC 可以从AB 调用。有没有办法知道 C 是从哪个 fragment 调用的?

已编辑

好的,伙计们,我要解释一下我要做什么。假设我有这样的调用:A 调用 B,B 调用 C。

当我在 C 中按下后退按钮时,它会将我带到 B,这很好。但是,当我再次按下后退按钮时,它会将我带到 C,而不是 A。

这是我的代码:

@Override
public void onBackPressed() { 

    //this is the current fragment
    Fragment fragmentActual =     this.getSupportFragmentManager().findFragmentById(android.R.id.tabcontent);

    String fragmentTag = fragmentoActual.getTag().toString();

            //If I press the back button in C:
    if(fragmentTag.equals("TAG C")){

        Fragment removefragment = this.getSupportFragmentManager().findFragmentByTag("TAG B");
        Fragment fragmentClient = this.getSupportFragmentManager().findFragmentByTag("TAG C");

        //If Im NOT passing arguments to B, I know this is a new form
        if(removefragment.getArguments()== null){

                            //I always pass arguments to fragment C, but just in case:
            if(fragmentClient.getArguments()!= null){

                Bundle mArguments = fragmentClient.getArguments();

                                    //FRAGMENT B
                FragmentB  fragmentB = new FragmentB ();
                fragment.setArguments(mArguments);

                FragmentManager manager = this.getSupportFragmentManager();
                FragmentTransaction ft = manager.beginTransaction();


                ft.addToBackStack(null);
                    ft.replace(android.R.id.tabcontent,fragmentB,"TAG B");
                    ft.commit();
                }
        }else{

            super.onBackPressed();
        }

    }else{
        super.onBackPressed();
    }

}   

现在我要解释代码。基本上它所做的是在调用 fragment C 时替换 fragment B。我这样做是因为我需要将参数传递给 fragment B。但是当我进行替换时, fragment B 的“历史记录”丢失了,我的意思是当我在 B 中按下后退按钮时,我无法返回到 fragment A < strong>(这就是为什么我想知道我是否能知道谁给谁打电话)。

当我第一次调用 fragment B 时,我没有传递参数,因为它是一个空白表单。但是当我调用 C 时,停留在 B 中,我需要将参数传递给 fragment B(当按下后退按钮时),因此它可以显示更新的信息。

如果有什么不清楚的地方,请告诉我,以便我更好地解释自己。

已编辑 2: 此问题与此 https://stackoverflow.com/questions/16703604/back-press-button-when-i-save-a-form-for-the-first-time-a-list-view-is-not-updat 有关.也许它让我的想法更清晰。

最佳答案

我认为 Luksprog 的回答是最好的:“您可能想要解决这些问题。您始终可以选择将带有数据的 Bundle 传递给新创建的 fragment ,并提及调用它的人。然后在fragment 会知道是谁调用了它。”。

我还没有找到其他更好的方法。

关于android - 如何知道哪个 fragment 称为另一个 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16718184/

相关文章:

android - 评级条 : same rating twice

java - 将操作栏添加到选项卡式布局

java - 自定义监听器/接口(interface)在 Android 中不起作用

android - 从拾取相机 Intent 回来后 fragment 已经激活

android - fragment 如何与上下文相关联?

android - 全新安装 Android Studio 后 Gradle 无法同步

android - 如何解决 : "cannot find getter for attribute ' android:text'"when implementing two-way data binding with custom view?

android - 将十六进制颜色字符串转换为颜色?

java - FragmentPagerAdapter 在第一页显示所有 fragment 内容

android - 未处理 fragment 的 AlertDialog 的单击事件中的自定义取消按钮