Android Fragment简介

1. 前言

Fragment是Android3.0后引入的一个新的API,为了适应大屏幕的平板电脑。使用Fragment可以把屏幕划分成几块,然后进行分组,进行一个模块化的管理。

2.Fragment的生命周期

Fragment相对于Activity多了onAttach()onDetach(),用于加载和释放资源。
这里写图片描述

3. Framgment加载方式

  • 静态加载

在布局文件中直接加载自定义fragment。FragmentLeft继承Fragment,在onCreateView()方法中定义界面。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
        android:id="@+id/fragment_left"
        android:name="com.blog.demo.component.act.FragmentLeft"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
  • 动态加载

假如在横屏情况下,我们可以加载不同布局文件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/fragment_left"
        android:name="com.blog.demo.component.act.FragmentLeft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <FrameLayout
        android:id="@+id/frame_right"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="match_parent" />
</LinearLayout>

使用FragmentManager对Fragment进行动态的加载。

if (findViewById(R.id.frame_right) != null) {
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.frame_right, new FragmentRight());
    ft.commitAllowingStateLoss();
}

猜你喜欢

转载自blog.csdn.net/chennai1101/article/details/81700968
今日推荐