Android应用开发中使用Fragment的入门学习教程

2019-12-10 18:59:17刘景俊

两个的生命周期很类似,也息息相关。
 
 
创建一个fragment你必须创建一个Fragment的子类或存在的子类,比如类似下面的代码

public static class AndroidFragment extends Fragment {
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) { 
    return inflater.inflate(R.layout.android_fragment, container, false);
 }
}

 

onCreate()
当fragment创建时被调用,你应该初始化一些实用的组件,比如在fragment暂停或停止时需要恢复的

onCreateView()
当系统调用fragment在首次绘制用户界面时,如果画一个UI在你的fragment你必须返回一个View当然了你可以返回null代表这个fragment没有UI.

那么如何添加一个Fragment到Activity中呢? Activity的布局可以这样写

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
 android:orientation="horizontal"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 <fragment android:name="com.android.cwj.ArticleListFragment"
   android:id="@+id/list"
   android:layout_weight="1"
   android:layout_width="0dp"
   android:layout_height="match_parent" />
 <fragment android:name="com.android.cwj.ArticleReaderFragment"
   android:id="@+id/viewer"
   android:layout_weight="2"
   android:layout_width="0dp"
   android:layout_height="match_parent" />
</LinearLayout>

 通常地 fragment做为宿主activity UI的一部分, 被作为activity整个view hierarchy的一部分被嵌入. 有2种方法你可以添加一个fragment到activity layout:

一、在activity的layout文件中声明fragment