随着Android平板的出现,为满足平板设备的UI灵活性设计要求,Fragment被引入到API 11级中。
支持库位于libs/android-support-v4,jar中,创建初期该jar包会自动添加到项目中。
那么在一个Activity中如何托管一个UI Fragment
两种方法:
第一种:添加Fragment到Activity的布局中
第二种:在activity代码中添加fragment
第一种方式就是在布局中使用fragment,这种方式虽然简单但是灵活度不够。将fragment添加到activity的布局中,就等同与将fragment及其视图与activity的视图绑定在一起,且在activity的生命周期中,无法切换Fragment视图。
主要不足之处就是在于灵活度不够。
第二种方式是一种比较复杂的托管方式,但也是唯一一种在运行时控制Fragment的方式。我们可以决定何时将fragment添加到Activity中以及随后可以完成各种任务。当然也可以移除Fragment,不同的Fragment之间的相互替换。
优点在于:运行时管理,灵活度比较高。
There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.