【问题标题】:Passing a listener through a chain of Fragments?通过一系列片段传递听众?
【发布时间】:2017-02-15 22:49:01
【问题描述】:

我希望能够定义一个侦听器(Activity、Fragment 等),并能够在我决定最终调用回调之前将其传递给任意数量的嵌套 Fragment。这样它就可以调用callback.someFunction(),并且不需要知道回调附加到什么ActivityFragment

不过,现在看来,通过一堆Fragments 发送侦听器没有什么好的方法。我最初考虑将它传递给构造函数,但随后监听器引用将在屏幕旋转等配置更改时被取消。

然后我考虑了 onAttach() 方法,但这些方法只能让您访问基础 Activitycontext,这也不一定符合我的要求。

我还考虑通过newInstance() 传递侦听器(这通常是保存传递到Fragments 的参数的方式,因为getArguments() 的内容通过Bundle 保留了配置更改),但我看不到任何将监听器保存在参数Bundle 中的好方法。

我能做什么?

【问题讨论】:

    标签: android android-fragments android-activity callback listener


    【解决方案1】:

    您应该做的是在发生配置更改或重新创建活动并恢复其实例状态时重新创建所有内容...这与此相同...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitivyt_layout);
    
        if(savedInstanceState != null){
            //1. restore instance state here
            savedInstanceState.getString("whatever");
    
           //2. try to find the fragment 
           Fragment f = getSupportFragmentManager().findFragmentByTag("FRAGMENT TAG");
    
            //3. make sure the fragment is correctly set up if already loaded
            if(f != null){
                ((ConcreteFragmentType)f).setListener(your_listener);
                //bring the fragment to the front or show it using the fragment manager
            }
            //4. or else add a brand-new instance
            else{
                    ConcreteFragmentType c = ConcreteFragmentType.newInstance();
                    c.setListener(your_listener);
                    getSupportFragmentManager().beginTransaction()
                            .add(R.id.fragmentContainer, c)
                            .commit();
                }
        }
    }
    

    【讨论】:

    • 根据我的问题,这并不是我想要的
    • @user6935095 答案演示了如何在重新创建活动后恢复片段中的实例状态。我到底错过了什么?
    猜你喜欢
    • 2012-06-02
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多