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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句