Fragment

什么是Fragment?

Fragment不是Activity,但是需要内嵌到Activtiy中,Fragment不是容器(viewGroup或者其子类),通常Fragment创建ViewGroup.
Fragment代表的是一种行为或者Activity的用户界面的一部分。

为什么要使用Fragment呢?

Android是在3.0时引入的Fragment,为了更好的支持大屏幕设备(平板)。使用Fragment来封装UI和Java代码,提高了复用性。

什么时候使用Fragment呢?

  • 逻辑共享:不同设备和屏幕尺寸之间共享UI和逻辑,通常用于平板电脑
  • 回退导航:把fragment添加到堆栈中,当回退时,就会出栈,这种实现方式避免了activity的重建
  • 整体滑动的效果:与ViewPager一起使用实现整体滑动的效果

怎么使用Fragment呢?

可以查看 Androidbase / Fragment / FragmentExample /下的FirstFragment相关的代码

  • 在activity的布局文件中声明 这种方式就好像fragment是一个View一样,但这种方式缺乏灵活性,不能动态的更改fragment,较少使用。
<?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:name="com.example.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>  

The android:name attribute in the <fragment>specifies the Fragment class to instantiate in the layout. When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the onCreateView() method for each one, to retrieve each fragment's layout. The system inserts the View returned by the fragment directly in place of the <fragment> element.

NOTICE: Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:

  1. Supply the android:id attribute with a unique ID.
  2. Supply the android:tag attribute with a unique string.
  3. If you provide neither of the previous two, the system uses the ID of the container view.
  • 通过java代码方式添加fragment到一个ViewGroup中 在Activity运行时可以动态的向Activity的布局中添加fragment,只需要指定fragment位于ViewGroup
/*1.获取FragmentManager*/
FragmentManager fragmentManager = getFragmentManager();
/*2.获取FragmentTransaction对象*/
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
/*3.创建fragment对象*/
ExampleFragment fragment = new ExampleFragment();
/*4.添加fragment*/
fragmentTransaction.add(R.id.fragment_container, fragment);
/*5.提交*/
fragmentTransaction.commit();

Fragment的生命周期

fragment生命周期与activity生命周期息息相关。
代码可以查看 Androidbase / Fragment / FragmentExample /下的FirstFragment相关的代码进行测试
一副图看懂看懂全部
查看图片

参考文档

参考文档

updatedupdated2020-06-132020-06-13