Android Fragment 初步解析
Fragment经常在我们的开发中见到,但是自我感觉对Fragment的理解还是处于初级的阶段,接下来我将用几篇文章尽量深的解析Fragment
让我们开始吧!!!
Fragment拥有自己的生命周期和接收、处理用户的事件,生命周期我们就用官网的一张图来展示一下
这张图对我来说还是比较好记的,他把周期分成基本的三大块吧
怎么样相对来说这样还是不错的吧~~~
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent" >
5
6 <fragment
7 android:id="@+id/id_fragment_title"
8 android:name="com.fragments.TitleFragment"
9 android:layout_width="fill_parent"
10 android:layout_height="45dp" />
11
12 <fragment
13 android:layout_below="@id/id_fragment_title"
14 android:id="@+id/id_fragment_content"
15 android:name="com.fragments.ContentFragment"
16 android:layout_width="fill_parent"
17 android:layout_height="fill_parent" />
18
19 </RelativeLayout>
主要是标黄的部分,这里在xml中静态的写入Fragment的路径,这样就能够引入到布局中,顺便看一下布局中还能直接写fragment标签,以前也知道,但是长时间不用都忘记了,这次正好复习一下,但是这种方式在开发中使用的机率还是比较小的,下面的方式才是我们主要是用的方式。
如何动态的添加、更新、以及删除Fragment
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent" >
5
6 <FrameLayout
7 android:id="@+id/content"
8 android:layout_width="fill_parent"
9 android:layout_height="fill_parent"
10 android:layout_above="@id/id_ly_bottombar"
11 android:layout_below="@id/id_fragment_title" />
12
13 </RelativeLayout>
布局中主要使用的帧布局FreamLayout 这是用来承载Fragment的布局
Activity的主要代码
1 FragmentManager fm = getFragmentManager();
2 FragmentTransaction transaction = fm.beginTransaction();
3 mFragment = new ContentFragment();
4 transaction.replace(R.id.id_content, mFragment);
5 transaction.commit();
代码中的FragmentManager提供了对Fragment的动态管理,fm.beginTransaction()相当于数据库中的事物的解析
优质内容筛选与推荐>>