Android Fragment - tenji/ks GitHub Wiki

Android Fragment

一、定义

因为 Android 设备尺寸大小不一 同一应用在不同尺寸上显示会有很大差异,Fragment 就是为了解决这个问题推出的。Fragment 可以看做是 Activity 界面的一部分,它有属于自己的生命周期和事件处理机制而且它可以动态的添加、替换、移除。此处补充一个官方定义:

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running.

Fragment 是依赖于 Activity 的,不能独立存在的。一个 Activity 里可以有多个 Fragment。一个 Fragment 可以被多个 Activity 重用。Fragment 有自己的生命周期,并能接收输入事件。我们能在 Activity 运行时动态地添加或删除 Fragment。

二、生命周期

三、使用方法

3.1 静态

资源文件中使用 Fragment 标签。

Step 1:定义 Fragment 的布局,就是 Fragment 显示内容的;

Step 2:自定义一个 Fragment 类,需要继承 Fragment 或者他的子类,重写 onCreateView() 方法 在该方法中调用 :inflater.inflate() 方法加载 Fragment 的布局文件,接着返回加载的 View 对象;

public class Fragmentone extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment1, container,false);
    return view;
    }
}

Step 3:在需要加载 Fragment 的 Activity 对应的布局文件中添加 Fragment 的标签, 记住,name 属性是全限定类名哦,就是要包含 Fragment 的包名。

Step 4:Activity 在 onCreate( ) 方法中调用 setContentView() 加载布局文件即可。

3.2 动态

编写代码将 Fragment 动态添加至现存的 ViewGroup。

Fragment 以及布局代码就不贴出来了,直接贴 MainActivity 的关键代码:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Display dis = getWindowManager().getDefaultDisplay();
        if(dis.getWidth() > dis.getHeight())
        {
            Fragment1 f1 = new Fragment1();
            getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f1).commit();
        } else {
            Fragment2 f2 = new Fragment2();
            getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f2).commit();
        }
    }
}

四、Fragment 管理与 Fragment 事务

4.1 FragmentManager

待更新...

4.2 FragmentTransaction

待更新...

五、Fragment 与 Activity 交互

5.1 组件获取

待更新...

5.2 数据交互

待更新...

六、Fragment 使用注意事项

待更新...

七、Fragment 嵌套使用

八、Fragment 使用模式

8.1 单 Activity + 多 Fragment

  • 优点:单 Activity 占用内存、资源少,性能高,速度最快。(如:新版知乎 、Google 系 App)
  • 缺点:逻辑比较复杂,尤其当 Fragment 之间联动较多或者嵌套较深时,比较复杂。

8.2 分模块 Activity + 多 Fragment

分模块,每个模块用单 Activity + 多 Fragment 组成,这样既有利于减少内存占用又降低应用难度。

  1. 登录注册流程:

    LoginActivity + 登录 Fragment + 注册 Fragment + 填写信息 Fragment + 忘记密码 Fragment

  2. 数据展示流程:

    DataActivity + 数据列表 Fragment + 数据详情 Fragment + …

速度快,相比较单 Activity + 多 Fragment,更易维护。

九、Fragment 系统提供的子类

参考链接