`

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中,本文暂不说明,因为作者还未明白。

 

 

 

 

 

 

 

 

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics