Fragment的一些注意事项
我们注意到,使用Fragment的时候,传参数是利用argument,而不是直接通过构造方法传参,那是为什么呢?
实际上,因为fragment的生命周期依赖于Activity,假如Activity销毁重建(屏幕旋转),Fragement也要创建的,这个时候,按照官方文档的说法,只有无参构造函数才会被调用。那么问题就很清晰了,自然是不能利用构造函数传参的。
官方描述如下:
Fragment ()
Default constructor. Every fragment must have an empty constructor, so it can be instantiated when restoring its activity’s state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().
add()和replace()
- add()是添加,多个fragment添加没有hide的话可以显示的都会显示
- replace()是替换
FragmentTransaction.addToBackStack(),可以将fragment添加到返回栈,比如A跳转到B,B返回到A就可以用到,只要在commit()之前添加到返回栈就可以,但是恢复的时候fragment实例虽然在,但是视图会重新绘制