android-discuss icon indicating copy to clipboard operation
android-discuss copied to clipboard

我想让Fragment在旋转後可以保留注册过的Callback,但就是找不到方法

Open siralam opened this issue 7 years ago • 6 comments

事情是这样的,大家都知道如果想让Fragment在旋转後还能保留之前的参数,我们就不能用 new Fragment()这种传统的构造器,而是需要newInstance(),然後把参数放到Bundle里面,再在适当的生命周期里面提取出来。

可是,当我想把一个callback (interface)传进去的时候,实在是找不到办法。因为Bundle能接受的东西有限嘛。

我尝试过让我那个自定义的接口extends Serializable,可是当Fragment在尝试saveState的时候就报错了: Parcelable encountered IOException writing serializable object

当然了,最基本的方法是让Activity implements 这个接口,然後让Fragment在onAttach()的时候注册这个callback。这个方法是ok的,可是只限於Activity,当你想在 AFragment 里呼叫这个Fragment的时候,即便你的 AFragment implements 这个接口,还是没有用,因为onAttach()一定是 attach to Activity的。

请问有什麽方法可以让Fragment呼叫Fragment的时候,可以把callback传进去,而且又能在装置旋转後保留这个callback?

siralam avatar May 10 '18 04:05 siralam

想到了,只要同时在onCreate()的时候,用getParentFragement()再看一次是否有注册Callback就可以了。

siralam avatar May 10 '18 07:05 siralam

eventbus 不行吗

iielse avatar Jun 13 '18 02:06 iielse

按我理解eventbus就是一大堆broadcast receiver, 所以应该可以,不过我没在用。

siralam avatar Jun 13 '18 03:06 siralam

setRetainInstance(true) 可以让Fragment 在配置变更时 实例得以保存。

biubiuqiu0 avatar Oct 14 '18 02:10 biubiuqiu0

可以用ViewModel来保存吧

luili16 avatar Oct 25 '18 10:10 luili16

还有些parentFragment

On Thu, Oct 25, 2018, 18:09 Tim [email protected] wrote:

可以用ViewModel来保存吧

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/android-cn/android-discuss/issues/701#issuecomment-432993939, or mute the thread https://github.com/notifications/unsubscribe-auth/AEMXQHyWCXrgD_X11vKH9G8FzIu4JAc-ks5uoY3mgaJpZM4T5W6L .

ipcjs avatar Oct 25 '18 13:10 ipcjs