Fragment的使用方法

作者: 仍是少年呀 | 来源:发表于2016-04-20 23:10 被阅读599次

简述Fragment

什么是Fragment
fragment 在英语中是碎片的意思,他是基于activity的一种控件。一个fragment对应着它自己的.xml布局文件来描述它的布局和.java文件来继承Fragment这个类。因为fragment基于activity且可以动态加载的缘故,它常被用来设计一些需要在一个activity内实现页面内切的app,比如

页面内切.png
平板设备的一般布局.png

或者一些为大屏幕设备如平板等打造的app,比如QQ HD


QQ HD

在这些布局中,用一个Activity承载了很多个动态的Fragment,可增可减,这样做,即减少了activity的负担,又更加能够体现MVC设计框架中View层的灵活性,让程序的界面设计更加模块化,易于开发和维护。
Frgment的生命周期(Lifecycle)
Android官方API文档中很详细的讲解了Fragment的生命周期,点击标题链接便可以访问。在此简述如下:

Lifecycle
可以看到Fragment比Activity多了几个额外的生命周期回调函数:

onAttach(Activity);//当Activity与Fragment发生关联时调用
onCreateView(LayoutInflater,ViewGroup,Bundle);//创建该Fragment的视图
onActivityCreate(bundle);//当Activity的onCreate();方法返回时调用
onDestoryView();//与onCreateView相对应,当改Fragment被移除时调用
onDetach();//与onAttach()相对应,当Fragment与Activity的关联被取消时调用
注意:除了onCreateView,其他的所有方法如果你重写了,必须调用父类对于该方法的实现。

创建Fragment

  • 1 静态的使用Fragment
    首先我先创建了一个空的Activity
    MainActivity

接着我又创建了两个Fragment的.xml文件,分别是fragment1.xml,和fragment2.xml


Layout fragment1 fragment2
<?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:fitsSystemWindows="true"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
            android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <fragment
        android:name="com.example.fuerm.myapplication.Fragment1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="50"
        tools:layout="@layout/fragment1" />

    <fragment
        android:name="com.example.fuerm.myapplication.Fragment2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="50"
        tools:layout="@layout/fragment2" />

</LinearLayout>


在Activity的布局代码中,我们将两个fragment直接像当作普通部件一样,放入Activity的Layout中,在此我在MainActivity中采用了垂直线性布局,LayoutWight各占50%,代码如上,MainActivity的布局效果如下图

MainActivity

以上就是Fragment静态的使用方法。

  • 2 Fragment的动态使用方法
    接下来,我们创建另一个工程,带有侧边汉堡菜单的APP.如图
    image.png

我们想实现当侧边汉堡菜单弹出时,点击汉堡菜单的按钮,主Activity的内容也相应改变。
首先还是想刚才一样创建两个Fragment.
然后再分别创建两个继承自Fragment的类 Fragment1 和Fragment2.
代码如下:

public class Fragment1 extends Fragment{
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

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

        View v = inflater.inflate(R.layout.fragment2,container,false);
        return v;
    }
}

然后我们需要在layout_content中添加一个布局,以作Fragment的Container.这个布局可以是LinearLayout,RelativeLayourt,FrameLayout或者其他,在此以FrameLayout为例,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:id="@+id/fragment_container"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="@layout/app_bar_main"
    tools:context=".MainActivity"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

然后我们整个屏幕都用来显示Fragment,所以其余的东西什么都不加。
然后,我们需要在MainActivity.java中去创建 这两个Fragment并动态的加载它们。

Fragment1 fragment1;    //创建一个Fragment1对象
Fragment2 fragment2;    //创建一个Fragment2对象
FragmentTranscation f;  //创建一个FragmentTranscation对象,这个是用来动态加载Fragment的

之后在MainActivity.java中的 onNavigationItemSelected(MenuItem item) 方法中,我们加入如fragment动态切换的方法:

@Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        f = getFragmentManager().beginTransaction();  //给f初始化
        fragment1 = new Fragment1();                  //对象初始化
        fragment2 = new Fragment2();                  //对象初始化
        //建议用switch语句,这是系统自己生成的
        if (id == R.id.nav_camara) {
            //以下是重点
            f = getFragmentManager().beginTransaction();//调用FragmentManager,并开始事务处理
            f.replace(R.id.fragment_container, fragment1);//替换一个fragment给我们的FrameLayout,这里需要说明一下,正常逻辑你应该在你的OnCreat( )方法中去实现FramLayout的初始布局。方法和如下是一样的
            f.commit();//提交事务
        } else if (id == R.id.nav_gallery) {
            f.replace(R.id.fragment_container, fragment2);//替换
            f.commit();
            //因为我们就两个fragment,而菜单数多余我们,仅仅为了展示,下面的就不管了
        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

总结一下

动态的使用需要调用FragmentTranscation的FragmentMannger,通过getFragmentManager( )获得,然后以提交事务的方式commit( )来添加add( )/replace( )或替换当前布局中的页面。

现在程序可以跑起来了,效果如下


Screenshot_2016-04-20-22-55-40.png Screenshot_2016-04-20-22-55-57.png

相关文章

网友评论

    本文标题:Fragment的使用方法

    本文链接:https://www.haomeiwen.com/subject/hxxtrttx.html