用fragment进行UI管理
步骤:
1、为了兼容,将主activity继承自FragmentActivity。
2、在activity的视图层结构中为fragment视图安排位置(定义容器视图)
3、创建UI fragment
(1)定义布局文件。(P118,119)
(2)创建fragment类,设置其视图为定义的布局。并在fragment类中关联布局文件中生成的组件。
即在fragment类中:
*实现fragment的生命周期方法(P120,121)
覆盖onCreate()方法和onCreateView()方法
*关联组件(P121)
在类中实例化组件,v.findViewById(R.id.… …)关联,最后设置事件监听器。
4、添加UI fragment到FragmentManager
(1)实例化一个FragmentManager。(P123)
FragmentManager fragmentManager=getSupportFragmentManager();
(2)创建transaction事务、处理transaction、提交transaction事务。(处理包括:添加,附加,分离,替换,隐藏)(P123下黑体代码)
if(fragment==null){
fragment=new XXFragment;
fragmentManager.beginTransaction().add(R.id.fragmentContainer,fragment).commit(); //此处连写了,可分开
}