简介

是从Android3.0开始新增的概念, 意为碎片,
而且是因为专门为平板设计的

用来组建Activity界面的局部模块,
也可以说一个Actiivty界面可以由多个Fragment组成

其行为与Activity很相似, 有自己对应的View,
它有自己的生命周期,接收自己的输入事件,你可以添加或移除从运行中的activity
一个fragment必须总是嵌入在一个activity中,
同时fragment的生命周期受activity的影响
本质上会产生一个FrameLayout,它加载的布局为其子布局/View
比如之前在手机显示一个列表,我们点击一下会进入详情页面
但是现在就不一样了,平板出来后,屏幕很大,我们没有必要在
那么大的屏幕显示一条数据,现在我们使用fragment将屏幕分成两部分
一部分显示列表数据,另外一部分显示详情数据

Android:Fragment(碎片)的简单使用,Fragment的生命周期_bundle

android-support-v4.jar

这个jar包是干嘛的呢?
它是google提供的能兼容到api4(1.6)的兼容jar包
在Android3.x加入了很多的API,但是在2.x和1.x的jar包里面
不支持3.x的API,那么google就将它们抽取出来,然后是项目中
使用这个jar,那么项目在打包的时候就会将这个jar也打包到项目里面
那么在低版本的手机也可以使用新的API,实现兼容性

这个android-support-v4.jar里面有两个重要的类:

API

Fragment
View onCreateView()
onActivityCreate() 当Activity创建好
getActivity()
setArguments()
getArgument()
ListFragment
setListAdapter(adapter)
onListItemClick()
getFragmentManager()
FragmentActivity
getSupportFragmentManager()
FragmentManager
beginTransacation()
FragmentTransacation
add(), replace(), remove(),commit()
addToBackStack()

使用

Fragment的静态加载

定义Fragment的子类, 并在onCreateView()中加载一个布局文件
在布局文件中通过<fragment>指定指定自定义Fragment
Activity必须继承于FragmentActivity
package com.jane.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyFragment1 extends Fragment
{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{

// 加载布局得到View对象并返回

// 创建一个视图对象, 设置数据并返回
TextView textView = new TextView(getActivity());
textView.setText("fragment11111");
textView.setBackgroundColor(Color.RED);

return textView;
}
}
package com.jane.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyFragment2 extends Fragment
{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{

// 加载布局得到View对象并返回

// 创建一个视图对象, 设置数据并返回
TextView textView = new TextView(getActivity());
textView.setText("fragment22222");

return textView;
}
}
package com.jane.fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

/*
* 测试使用Fragment(静态加载)
* 1. 定义Fragment的子类, 并加载一个布局文件
* 2. 在布局文件中通过<fragment>指定指定自定义Fragment
* 3. 我们的Activity必须继承于FragmentActivity
* 每个Fragment本质上都会生成一个FrameLayout, 它加载的布局为其子布局
*/
public class MainActivity extends FragmentActivity
{

public MainActivity()
{
Log.e("TAG", "MainActivity()..");
}

@Override
protected void onCreate(Bundle savedInstanceState)
{
Log.e("TAG", "MainActivity onCreate()..");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">

<fragment
android:name="com.jane.fragment.MyFragment1"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent" />

<fragment
android:name="com.jane.fragment.MyFragment2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent" />

</LinearLayout>

Fragment的动态加载

package com.jane.fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;

/**
* 测试使用Fragment(动态使用)
* 1. 使用FragmentManager和FragmentTransaction动态使用一个Fragment
* 2. 方式:
* add(viewId, fragment): 将fragment的视图添加为指定视图的子视图(加在原有子视图的后面)
* replace(viewId, fragment): 将fragment的视图添加为指定视图的子视图(先remove原有的子视图)
* remove(fragment) : 将fragment的视图移除
*/
public class MainActivity extends FragmentActivity
{

public MainActivity()
{
Log.e("TAG", "MainActivity()..");
}

@Override
protected void onCreate(Bundle savedInstanceState)
{
Log.e("TAG", "MainActivity onCreate()..");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// 创建Fragment对象
MyFragment1 fragment1 = new MyFragment1();
// 得到FragmentManager
FragmentManager manager = getSupportFragmentManager();
// 得到FragmentTransacation
FragmentTransaction transaction = manager.beginTransaction();
// 添加Fragment对象并提交
transaction.add(R.id.ll_main_container, fragment1).commit();
}

private MyFragment2 fragment2;

public void showFragment2(View v)
{
// 创建Fragment对象
fragment2 = new MyFragment2();
// 得到FragmentManager
FragmentManager manager = getSupportFragmentManager();
// 得到FragmentTransacation
FragmentTransaction transaction = manager.beginTransaction();

// 将当前操作添加到回退栈, 这样点击back回到上一个状态
transaction.addToBackStack(null);

// 替换Fragment对象并提交
transaction.replace(R.id.ll_main_container, fragment2).commit();
}

public void deleteFragment2(View v)
{

// 得到FragmentManager
FragmentManager manager = getSupportFragmentManager();
// 得到FragmentTransacation
FragmentTransaction transaction = manager.beginTransaction();
// 移除Fragment对象并提交
transaction.remove(fragment2).commit();
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="showFragment2"
android:text="显示fragment2" />

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="deleteFragment2"
android:text="移除fragment2" />
</LinearLayout>

<LinearLayout
android:id="@+id/ll_main_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
</LinearLayout>

</LinearLayout>

Fragment的生命周期

Android:Fragment(碎片)的简单使用,Fragment的生命周期_android_02

测试
/*
添加Fragment对象显示
onAttach()-->onCreate()-->onCreateView()-->onActivityCreated()-->onstart()-->onResume()
home到桌面
onPause()-->onStop()
回到应用
onStart()-->onResume()
replace为其它Fragment
onPause()-->onStop()-->onDestroyView()
返回到本身的Fragment
onCreateView()-->onActivityCreated()-->onstart()-->onResume()
退出应用
onPause()-->onstop()-->onDestroyView()-->onDestroy()-->onDetach()
*/

模仿平板样子

首先准备好数据
package com.jane.fragment;

public class DataUtils
{
public static final String[] TITLES =
{ "title1", "title2", "title3", "title4", "title5" };
public static final String[] DETAILS =
{ "This is title1", "This is title2", "This is title3", "This is title4",
"This is title5" };
}
然后是主界面
package com.jane.fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
<?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="horizontal" >

<fragment
android:name="com.jane.fragment.TitleListFragment"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent" />

<FrameLayout
android:id="@+id/fl_main_container"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="match_parent" >
</FrameLayout>

</LinearLayout>
然后是主界面需要的主题显示列表
package com.jane.fragment;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
* 用来显示标题的列表
*/
public class TitleListFragment extends ListFragment
{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);

// 设置ListView为单选模式
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

// 给listView设置adapter显示列表
setListAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.list_item, DataUtils.TITLES));

// 默认选中第一个item
getListView().setItemChecked(0, true);
// 显示第一个详情
showDetail(0);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id)
{
showDetail(position);
}

/**
* 显示指定下标的详情
* @param position
*/
private void showDetail(int position)
{
// 创建DetailFragment
DetailFragment fragment = new DetailFragment();
// 将对应的详情数据携带过去
Bundle args = new Bundle();
args.putString("DETAIL", DataUtils.DETAILS[position]);
fragment.setArguments(args);
// 将其替换到id为fl_main_container的容器布局中
getFragmentManager().beginTransaction()
.replace(R.id.fl_main_container, fragment).commit();
}
}
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textSize="18sp"
android:gravity="center"
android:text="标题"
android:background="?android:attr/activatedBackgroundIndicator">
<!-- android:background="?android:attr/activatedBackgroundIndicator"
这行是用来让选择项变色的
-->
</TextView>
然后是详情的Fragment
package com.jane.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
* 显示详情的Fragment
*/
public class DetailFragment extends Fragment
{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
TextView textView = new TextView(getActivity());
// 取出保存的数据
String detail = getArguments().getString("DETAIL");
// 设置
textView.setText(detail);
return textView;
}
}