保存实例状态
对于 Integer、Long、String 等数据,我只是将其放入 bundle 中,并在再次调用 onCreateView 时将其取回。但是我的 fragment 也有像下面这样的听众,
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.
}
我怎样才能让监听器 bundle 以便稍后取回它?
最佳答案
我最近刚刚找到了执行此操作的正确方法,我想与该主题的 future 读者分享。
保存 fragment 监听器的正确方法不是保存它,而是当 fragment 附加到 Activity 时从 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();
}
}
- 当 fragment 附加到 Activity 时,我们检查 Activity 是否实现了 TheFragmentContainer
- 如果 Activity 有,则向 Activity 请求监听器。
关于android - onSaveInstanceState 中的保存接口(interface)(Listener),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21043159/