在onSaveInstanceState中保存接口(侦听器) [英] Save interface (Listener) in onSaveInstanceState

查看:78
本文介绍了在onSaveInstanceState中保存接口(侦听器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SaveInstanceState

对于像Integer,Long,String之类的数据,其他都很好,我只是将其放入包中,并在再次调用onCreateView时将其取回.但是我的片段也有如下的监听器,

For data like Integer, Long, String and else are fine, I just put it in the bundle and get it back once the onCreateView gets called again. But my fragment also has listener like following,

public class SomeFragment extends Fragment {
    public interface SomeListener {
        public void onStartDoingSomething(Object whatItIsDoing, Date when);
        public void onDoneDoingTheThing(Object whatItDid, boolean result);
    }

    private SomeFragmentListener listener;
    private String[] args;

    public static SomeFragment getInstance(SomeListener _listener, String... _args) {
        SomeFragment sf = new SomeFragment();
        sf.listener = _listener
        sf.args = _args

        return sf;
    }

    // rest of the class

    // the example of where do I invoke the listener are
    // - onSetVisibilityHint
    // - When AsyncTask is done
    // - successfully download JSON
    // etc.
} 

我如何捆绑听众,以便以后可以找回它?

How can I have the listener to bundle so that I can get it back later?

推荐答案

我最近找到了执行此操作的正确方法,并希望与以后分享该主题的读者共享.

I recently just found the proper way to do this and I want to share for future reader of this topic.

保存片段侦听器的正确方法不是保存片段,而是在片段附加到活动时从活动请求.

The proper way to save listener of the fragment is not to save it, but instead, request from activity when fragment got attached to activity.

public class TheFragment extends Fragment {
    private TheFragmentListener listener;

    @Override
    public void onAttach(Context context) {
        if (context instanceof TheFragmentContainer) {
            listener = ((TheFragmentContainer) context).onRequestListener();
        }
    }

    public void theMethod() {
        // do some task
        if (listener != null) {
            listener.onSomethingHappen();
        }
    }

    public interface TheFragmentContainer {
        public TheFragmentListener onRequestListener();
    }

    public interface TheFragmentListener {
        public void onSomethingHappen();
    }
}

  • 片段连接到活动时,我们检查活动是否实现TheFragmentContainer
  • 如果活动确实有,请从活动中请求侦听器.
  • 这篇关于在onSaveInstanceState中保存接口(侦听器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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