首页 > 学院 > 开发设计 > 正文

Fragment的概述

2019-11-09 18:09:38
字体:
来源:转载
供稿:网友
Fragment是Activity的一部分,在Activity的内部使用。一个Activity里面可以有多个Fragment;同时,一个Fragment也可以应用于多个Activity。Fragment的生命周期依赖于Activity。当添加一个Fragment到Activity的布局里时,它是被放在ViewGroup(是一个容器)里,Fragment会定义它自己的视图布局。Fragment是Android3.0(API 11)时引入的。Fragment的作用:主要是为了在大屏幕上支持更多的动态和灵活的UI设计。如在平板电脑上。Fragment是相对于Activity属于轻量级的,所以一个好的APP最好是Activity越少越好,其他全用Fragment来做。创建一个Fragment类的基本步骤:1.创建fragment类让其继承Fragment2.通过onCreateView()方法加载fragment要显示的内容。(相当于Activity的setContentView()方法)3.在onCreateView里通过布局填充器inflater的inflate()方法把布局文件转换成一个View对象。4.在onCreateView里把View对象返回出去。代码如下:
public class Fragment1 extends Fragment {    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View fragment1 = inflater.inflate(R.layout.fragment1, null);        return fragment1;    }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表