在onSaveInstanceState中保存接口(Listener)

问题描述 投票:6回答:2

SaveInstanceState

对于像Integer,Long,String等数据都很好,我只是把它放在bundle中,一旦再次调用onCreateView就把它取回来。但我的片段也有听众如下,

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.
} 

如何让侦听器捆绑以便以后可以将其取回?

android activity-lifecycle fragment-lifecycle
2个回答
6
投票

我最近刚刚找到了正确的方法,我想分享这个主题的未来读者。

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

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
  • 如果活动有,请从活动请求监听器。

1
投票

Bundle中没有合适的.put方法的任何类都需要实现Serializable(就像在其中使用的任何对象一样)或实现Parcelable(后者是首选)。然后,您可以在Bundle上使用putParcelable或putSerializable方法。

© www.soinside.com 2019 - 2024. All rights reserved.