开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第5天,点击查看活动详情
1.Fragment的介绍
Android在3.0版本引入了Fragment功能,它非常类似于Activity,可以像Activity一样包含布局。
它出现的初衷是为了适应大屏幕的平板电脑,使用Fragment我们可以把屏幕划分成几块,合理利用屏幕空间。
Fragment通常是嵌套在Activity中使用。
使用要点: Fragment并不能单独使用,他需要嵌套在Activity中使用,作为Activity界面的一部分组成出现。
可以在一个Activity中同时出现多个Fragment,并且一个Fragment也可以在多个Activity中使用。
在Activity运行过程中,可以通过transaction的add()、remove()。replace()方法来添加,移除,或者替换Fragment。
2.静态加载
步骤:
(1)定义Fragment控件的布局文件。
<FrameLayout 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=".LeftFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是左边" />
</FrameLayout>
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RightFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是右边" />
</FrameLayout>
(2)自定义Fragment类,继承自Fragment类或者子类,同时实现onCreateView()方法,在方法中,通过inflater.inflate加载布局文件,接着返回其View。
(3)在需要加载Fragment控件的Activity对应的布局文件中添加Fragment标签,并设置name属性为自定义fragment。
<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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/leftFrag"
android:name="com.hui.fragment.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<fragment
android:id="@+id/rightFrag"
android:name="com.hui.fragment.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
(4)最后在Activity的onCreate()方法中调用setContentView()加载布局。
3.动态加载
步骤:
(1)通过getSupportFragmentManager()方法获得FragmentManager对象。
val fragmentManager=supportFragmentManager
(2)开启事务,通过beginTransaction()方法获得FragmentTransaction对象。
val transaction=fragmentManager.beginTransaction()
(3)调用add()方法或者repalce()方法加载Fragment。
transaction.replace(R.id.rightLayout,fragment)
//replace()方法需要传入容器的id和待添加的Fragment实例
(4)最后调用commit()方法提交事务。
transaction.commit()
4.Fragment的生命周期 运行状态 暂停状态 停止状态 销毁状态