Fragment
**
*1. 什么是Fragment?
Fragment可以叫为“片段”或“碎片”,表示Activity中的行为或用户界面部分。我们可以在一个Activity中用多个Fragment组合来构建多窗格。
2. 用Fragment解决什么问题?
- 使用Fragment可以在一个Activity中实现不同界面的灵活切换。
- 当一款APP同时推出手机版和Pad版,不需要再分别编写多套布局方案,通过Fragment设计的布局可以动态、灵活的解决不同屏幕分辨率的适配问题。
- 对于小白,想模仿一些APP里底部菜单框实现上面的页面跳转,只能用Activity来实现,这样就会有很繁琐的代码和错误,并且会有页面跳转的痕迹,这时用Fragment就可以很好的解决这一问题。
*3. Fragment静态加载方法(附代码)*
Fragment静态加载步骤:
1)新建类继承Fragement;
2)重写onCreateView;
3)使用LayoutInflater对象中的inflate方法绑定布局和控件;
4)在Activity对应的布局文件中通过<fragment>标签引用。代码演示:
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.pc.fragment.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="Hello World!"
android:textSize="30sp"
android:gravity="center"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:id="@+id/f_one"
android:name="com.example.pc.fragment.fragment.Fragmentone"
/>
<fragment
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:id="@+id/f_two"
android:name="com.example.pc.fragment.fragment.Fragmenttwo"
/>
</LinearLayout>
</LinearLayout>
创建两个Fragment类
Fragment的java代码:
package com.example.pc.fragment.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import