Fragment的重要的生命周期:
onAttach():主要用于fragment关联到Activity后的参数传值
onCreate():fragment的创建,注意不是Activity的创建完毕,这个时候并不能获取到Activity中的内容
onCreateView():创建fragment要加载的View
onActivityCreated():Activity创建完毕
onStart()、onResume()、onPause()、onStop():与Activity类似
onDetach():fragment生命周期最后一个回调方法
fragment有两种使用的方式,一种是在布局文件中直接饮用,另一种是动态加载fragment
先来演示一种静态加载fragment的方法,首先展示一下工程目录结构
主界面就是MainActivity,然后创建了一个FragmentTest,这个里面就是创建的一个fragment,这个需要继承Fragment,并且我使用的是support.v4的这个包,因为这个fragment的功能更加的全面,来展示一下代码:
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Created by czj01 on 2017/5/8. */ public class FragmentTest extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_list, container, false); } }
里面的函数onCreateView中会传进来三个参数,我们可以使用inflater来指定我们的fragment的显示。
然后就是MainActivity中的代码段:
mport android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void fragmentDemo(View view){ startActivity(new Intent(this,DemoFragmentActivity.class)); } }
以及DemoFragmentActivity中的代码段:
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class DemoFragmentActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo_fragment); } }这样我们的一个简单的静态加载fragment就实现了,但是需要注意的是DemoFragment的xml布局文件中,我们一定要指定这个布局的id,如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_demo_fragment" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.czj01.fragmentdemo.DemoFragmentActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="在XML中使用fragment"/> <fragment android:name="com.example.czj01.fragmentdemo.FragmentTest" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:layout="@layout/fragment_list"> </fragment> </LinearLayout>
其中的
android:id="@+id/activity_demo_fragment"这个id是一定要设置的,不然fragment在运行的时候,会报错。