android – 在onSaveInstanceState中保存接口(Listener)
作者:互联网
SaveInstanceState
对于像Integer,Long,String等其他数据都很好,我只需将它放入包中,并在再次调用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.
}
如何让侦听器捆绑以便以后可以将其取回?
解决方法:
我最近刚刚找到了正确的方法,我想分享这个主题的未来读者.
保存片段监听器的正确方法不是保存它,而是在片段附加到活动时从活动请求.
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
>如果活动有,请从活动请求监听器.
标签:android,activity-lifecycle,fragment-lifecycle 来源: https://codeday.me/bug/20190517/1120634.html