通过一系列片段传递听众?

时间:2016-10-07 03:05:17

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

我希望能够定义一个监听器(一个Activity,Fragment等),并且能够在我决定最终调用回调之前将它传递给任意数量的嵌套Frag。这样它就可以调用 div { border: 2px solid #C15649; width:20px; height:20px; position: relative; top:0; margin:0; padding:0; left:0; z-index: 1; text-align: center; color:black; border-radius: 50%; cursor: pointer; box-sizing: border-box; } div:before{ position: absolute; content:""; top:0; bottom:0; background:black; border-radius:50%; left:0; right:0; margin:auto; width:100%; height:100%; },并且不需要知道回调附加到的<div> </div>callback.someFunction()

但是现在似乎没有好办法通过一堆Activity发送监听器。我最初考虑将它传递给构造函数,但是随后的配置更改(如屏幕旋转)会使侦听器引用变为无效。

然后我考虑了Fragment方法,但这些方法只允许您访问基础Fragments的{​​{1}},这不一定是我想要的。

我还考虑通过onAttach()传递侦听器(这通常是如何保存传递到context的参数,因为Activity的内容通过newInstance()幸存了配置更改),但我没有看到任何在参数Fragments中保存监听器的好方法。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

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

@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();
            }
    }
}