Fragment的基本用法

一、Fragment主要用到的API:  

  1.Fragment 类-----用来创建碎片

  2.FragmentManager 类 ----为管理Activity中Fragment,用于Activity与Fragment之间进行交互.

  3.FragmentTransaction 类 ---用碎片管理器创建碎片事务,用碎片事务来执行碎片的添加,移除,替换,显示,隐藏等操作

二、fragment 可认为是一个轻量级的Activity,但不同与Activity,它是要嵌到Activity中来使用的,它用来解决设备屏幕大小的不同,主要是充分利用界面上的空间,如平板上多余的空间。一个Activity可以插入多个Fragment,可以认为Fragment就是Activity上的一个View。

  

三、Fragment的基本使用步骤

fragment 的布局文件===》fragment子类中用onCreateView()加载该布局===》在相应的Activity的布局文件中引用fragment===》在Activity中显示

上代码:

1.fragment 的布局文件:

myfragment.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical" >
 6 
 7     <TextView
 8         android:id="@+id/textView1"
 9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:text="我是碎片的视图"
12         android:textSize="30sp"/>
13 </LinearLayout>

2.fragment子类中用onCreateView()加载该布局:建一个Fragment的子类MyFrag,

 1 package com.robin.fragdemo.frag;
 2 
 3 import com.robin.fragdemo.R;
 4 import android.app.Fragment;
 5 import android.os.Bundle;
 6 import android.view.LayoutInflater;
 7 import android.view.View;
 8 import android.view.ViewGroup;
 9 
10 
11 public class MyFrag extends Fragment{
12     @Override//用加载器inflater把fragment 的布局文件myfrag.xml变成一个View.
13     public View onCreateView(LayoutInflater inflater, ViewGroup container,
14             Bundle savedInstanceState) {
15         View view=inflater.inflate(R.layout.myrag, container,false);
16         return view;
17     }
18 }

3.在相应的Activity的布局文件中引用fragment

  MainActivity的布局文件 face.xml 中引用fragment:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical" >
 6     
 7     <!-- fragment不是view只是占位符 -->
 8     <fragment 
 9         android:id="@+id/fragment"
10         android:name="com.robin.myfrag.frag.MyFragment"
11         android:layout_width="match_parent"
12         android:layout_height="wrap_content"/>
13 </LinearLayout>
com.robin.myfrag.frag.MyFrag------MyFrag的全类名。

4.在Activity中显示

 1 package com.robin.myfrag.act;
 2 
 3 import com.robin.myfrag.R;
 4 import android.app.Activity;
 5 import android.os.Bundle;
 6 import android.util.Log;
 7 
 8 public class MainAct extends Activity{
 9     @Override
10     protected void onCreate(Bundle savedInstanceState) {
11         super.onCreate(savedInstanceState);
12         setContentView(R.layout.face);
13     }
14 }

这就是Fragment的基本使用步骤。

原文地址:https://www.cnblogs.com/huaqing-wkc/p/4926288.html