您的位置:首页 > 移动开发 > Android开发

Android Fragment 基本介绍

2014-10-20 19:03 387 查看

Fragment

  Android是在Android 3.0 (API level 11)开始引入Fragment的。

  可以把Fragment想成Activity中的模块,这个模块有自己的布局,有自己的生命周期,单独处理自己的输入,在Activity运行的时候可以加载或者移除Fragment模块。

  可以把Fragment设计成可以在多个Activity中复用的模块。

  当开发的应用程序同时适用于平板电脑和手机时,可以利用Fragment实现灵活的布局,改善用户体验。

  如图:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn1"
/>

<fragment
android:name="com.example.learningfragment.ExampleFragment"
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content"

/>
<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn2"
/>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Button
android:id="@+id/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn3"
/>
</LinearLayout>

</LinearLayout>


  运行结果如下:



  可以看到第二种方式加入fragment的时候,指定了父容器(一个线性布局)的id,其中已经有一个Button 3,所以fragment加在其后。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: