Fragment时寄生在Activity里的,所以,Activity的生命周期会影响到Fragment的生命周期。Fragment有两种创建方式,分别是动态创建更静态创建,不管如果,我们都要先创建Fragment子类
1.创建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:background="@android:color/holo_red_light"
android:orientation="vertical" >
</LinearLayout>
然后新建个类继承Fragment,重写onCreateView方法,在方法里用打气筒将刚才那个布局打成View并且返回。
package com.hyw.test;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TestFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
}
2.让Fragment寄生到Activity里
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<fragment
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.hyw.test.TestFragment"/>
</RelativeLayout>
注意: 中的 android:name 属性指定要在布局中实例化的 Fragment 类。
然后,你还可以动态地把Fragment塞到Activity里,先获取FragmentManager
FragmentManager fragmentManager = getFragmentManager();
然后通过FragmentManager 开启一个事务
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
别忘了动态new一个Fragment
TestFragment fragment = new TestFragment();
最后通过FragmentTransaction把Fragment塞到你想塞到的地方并提交,那个地方需是ViewGroup,下面那个id就是那地方的id
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
不过,在您调用 commit() 之前,您可能想调用 addToBackStack(),以将事务添加到片段事务返回栈
fragmentTransaction.addToBackStack(null);
3.那么Activity跟Fragment怎么互相交流呢?
Fragment可以通过getActivity获取Activity然后执行Activity里的方法
View listView = getActivity().findViewById(R.id.list);
同样地,您的 Activity 也可以使用 findFragmentById() 或 findFragmentByTag(),通过从 FragmentManager 获取对 Fragment 的引用来调用片段中的方法。
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);