背景
前两篇文章,我们已经了解了Fragment的基本使用以及Fragment生命周期,今天我们来看一下Fragment与Activity之间是如何通信,其中包括Activity向Fragment发消息,以及Fragment如何向Activity发消息。通信的方式有很多种,包括广播,Eventbus等,我们今天就介绍其中用的最为广泛的两种方式。
Activity向Fragment传递消息。
在我们使用Fragment进行初始化的时候可能需要传递参数,从而使用带参的构造函数,然而这是一件十分危险的事情,官网的说法如下
All subclasses of Fragment must include a public no-argument constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the no-argument constructor is not available, a runtime exception will occur in some cases during state restore.
当Fragment由于某些原因,比如说屏幕翻转,导致Fragment被销毁需要重建的时候,会调用onCreate()方法获取之前的状态,然后调用无参的构造函数取重建Fragment,所以如果没有无参的构造函数就会发生异常。可以使用getArguments通过Bundle去避免这个问题。
我们还是使用之前的例子如下图