静态加载Fragment
1.创建一个类MyFragment继承自Fragment或者Fragment的子类
2.让MyFragment重写onCreateView()方法
此时MyFragment就相当于一个自定义View,可以在布局中使用
//一定要给它一个Id或者tag,name属性值就是你所创建的MyFragment全名
3.创建要加载该Fragment的Activity
4.为该Activity创建布局文件
1.创建一个类MyFragment继承自Fragment或者Fragment的子类
2.让MyFragment重写onCreateView()方法
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 将R.layout.fragment文件装换成View对象,该布局文件就是Fragment显示的内容
View view = inflater.inflate(R.layout.fragment, container, false);
return view;
}
此时MyFragment就相当于一个自定义View,可以在布局中使用
//一定要给它一个Id或者tag,name属性值就是你所创建的MyFragment全名
<fragment
android:id="@+id/fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.fragment.MyFragment"/>
3.创建要加载该Fragment的Activity
4.为该Activity创建布局文件
<?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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.fragment.MyFragment"/>
</LinearLayout>
动态加载Fragment
MyFragment2 fragment2 = new MyFragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
beginTransaction.add(R.id.frame, fragment2);
beginTransaction.addToBackStack(null); // 按下物理按键可以返回到上一个状态
beginTransaction.commit();