打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Android学习之——Fragment随堂笔记(一)

1.简介

Android 3.0 (API level 11)开始引入Fragment。

Fragment实际上可以算是Activity中的模块,它 有自己的布局、生命周期,可以单独处理自己的输入。可以设计在Activity中复用。

2.生命周期

      Fragment嵌入到Activity中使用,所以它的生命周期与它所在的Activity有关。

Activity暂停,其包含的全部Fragment都暂停;

Activity停止,其包含的全部Fragment都不能被启动;

Activity被销毁,其包含的所有Fragment都会被销毁。

当Activity出于活动状态时,内嵌在其中的Fragment可以独立进行控制,如移除、新增等。

3.Fragment的基本使用

1)Fragment的新建,定义一个类,继承Fragment, 调用noCreateView方法,然返回一个Fragments可使用的View

=>继承时要注意可使用的最低版本

=>android.app.Fragment最低向下支持Android3.0版本

=>android.support.v4.app.Fragment扩展包保证可向下兼容至Android2.0版本

=>代码如下:

package com.sj.fragmentsforandroid;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class New_Fragment extends Fragment {    @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container,      Bundle savedInstanceState) {    // TODO Auto-generated method stub    View view = inflater.inflate(R.layout.activity_01, container,false);        return view;  }}

onCreateView()方法中:

container参数表明当前Fragment在Activity中的父控件是谁;

savedInstanceState提供了之前使用的一个实例的数据。

onCreateView()方法调用了inflate()方法,它包含了三个参数:

R.layout.activity_01,是一个resource ID,是当前Fragment所对应的资源文件;

container,表示父容器控件;

第三个是布尔值参数,true表示要连接该布局和其父容器控件,false则不连接,系统已经插入了这个布局到父控件,所以此处设置为false,如果设置为true将会产生多余的一个ViewGroup。

2)添加Fragment到Activity,加载方式有两种

一种是使用标签<fragment> 在Activity的layout中声明, 将Fragment作为一个子标签加入。

示例如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical" >  <fragment    android:id="@+id/fragment_01"    android:name="com.sj.fragmentsforandroid.Fragment_01"    android:layout_width="wrap_content"    android:layout_height="100dp" />  <fragment    android:id="@+id/fragment_02"    android:name="com.sj.fragmentsforandroid.Fragment_02"    android:layout_width="wrap_content"    android:layout_height="100dp" /></LinearLayout> 

注意:这里面的android:name="com.sj.fragmentsforandroid.Fragment_02"中填上创建的完整的Fragment类名(包含了类所在的包名);同时,加载了多个fragment时,要记得给每一个都加上属于自己的id,否则就会提示id重复,从而导致出错。

另一种是通过编程的方式将Fragment加入到一个ViewGroup中,


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Android中Fragment的应用
android Fragments详解三:实现Fragment的界面
Android Dev Guide.Activities.Fragments文档章节翻译
Fragments
[转载]Android中Fragment的操做 android3.0 默认栏目 默认栏目 ...
android中fragment与activity之间通信原理以及例子
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服