打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Android Fragment简介

前言

Fragment是Android3.0后引入的一个新的API,为了适应大屏幕的平板电脑。使用Fragment可以把屏幕划分成几块,然后进行分组,进行一个模块化的管理。

1.Fragment的生命周期

Fragment相对于Activity多了onAttach(Context)onDetach(),用于加载和释放资源。

2. Framgment加载方式

  • 静态加载
    在布局文件中直接加载自定义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:id="@+id/fragment_left"          android:name="com.blog.demo.component.fragment.FragmentLeft"          android:layout_width="0dp"          android:layout_weight="1"          android:layout_height="match_parent" />  </LinearLayout>

    FragmentLeft继承Fragment,在onCreateView()方法中定义界面。

      <?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:orientation="vertical"      android:layout_width="match_parent"      android:layout_height="match_parent">      <TextView          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="fragment left"/>  </LinearLayout>
  • 动态加载

    假如在横屏情况下,我们可以加载不同布局文件。

      <?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:id="@+id/fragment_left"          android:name="com.blog.demo.component.fragment.FragmentLeft"          android:layout_width="0dp"          android:layout_height="match_parent"          android:layout_weight="1"/>      <FrameLayout          android:id="@+id/fragment_right"          android:layout_width="0dp"          android:layout_weight="2"          android:layout_height="match_parent" />  </LinearLayout>

    使用FragmentManagerFragment进行动态的加载。

      if (findViewById(R.id.fragment_right) != null) {      FragmentManager fm = getSupportFragmentManager();      FragmentTransaction ft = fm.beginTransaction();      ft.add(R.id.fragment_right, new FragmentRight());      ft.commitAllowingStateLoss();  }	
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Android UI 之 Tab类型界面总结
使用Fragment完成Tab选项卡
Android App 侧边栏菜单的简单实现
求教android实现短信图标右上角添加数字的问题。。跪求大神。。。
Android 自定义标题栏(title栏)
Android 用户表单融合各类简易控件以及融入FloatingActionButton以及butterknife
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服