Fragment(碎片)是一种嵌入在Activity中的UI片段,它可以用来描述Activity中的一部分布局。如果Activity界面布局中的控件比较多比较复杂,那么Activity管理起来就比较麻烦,我们可以使用Fragment把屏幕划分成几个片段,进行模块化的管理,从而使程序更加合理和充分地利用的空间。
Activity生命周期中有5中状态,分别是启动状态、运行状态、暂停状态、停止状态和销毁状态。
因为Fragment是被嵌入到Activity中使用的,因此它的生命周期的状态是直接受其所属Activity的生命周期状态影响。
Fragment生命周期与Activity的生命周期十分相似。Fragment生命周期比Activity多了以下几个方法,具体如下:
public class NewsListFragment extends Fragment{
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment,container,false);
return v;
}
}
上述代码重写了Fragment和onCreateView()方法,并在该方法中通过LayoutInflater的inflate()方法将布局文件fragment.xml动态加载Fragment中
Fragment创建完成后并不能单独使用,还需要将Fragment添加到Activity中。在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"
tools:context=".MainActivity"
>
<fragment
android:name="cn.itcast.NewListFragment"
android:id="@+id/newslist"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
当Activity运行时,也可以将Fragment动态添加到Activity中,具体步骤如下:
(1)创建一个Fragment的实例对象
(2)获取FragmentManager的实例
(3)开启FragmentTransaction
(4)向Activity的布局容器中添加Fragment
(5)通过commit()方法提交事务
在Activity中添加Fragment的代码如下:
public class MainActivity extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NewsListFragment fragment = new NewsListFragment();//实例化Fragment对象
FragmentManager fm = getFragmentManager();//获取FragmentManager实例
FragmentTransaction beginTransaction = fm.beginTransaction();//开启FragmentTransaction
beginTransaction.replace(R.id.ll,fragment);//添加一个Fragment
beginTransaction.commit();//提交事务
}
}
创建工程
创建一个名为SichuanCuisine的应用程序
放置界面控件
放置界面控件
创建两个Fragment的布局文件
创建川菜列表Item界面
创建ContentFragment
ContentFragment类继承自Fragment,在该类中获取界面控件并将菜品做法的数据显示在控件上
通过setText()方法将获取的Activity中设置的菜品做法数据信息显示到界面控件上,创建一个initView()方法,在该方法中获取菜品做法信息的控件
文章目录 前言 本周最重要的五件事情 本周搞砸的四件事情 本周的四个启发 前言 ...
在项目开始之前我们可以先去了解一下IConfiguration接口,.Net Core Web应用程序...
JSP spring boot / cloud 使用filter防止XSS 一.前言 XSS(跨站脚本攻击) 跨站脚...
一.前言 .NET Core 是一个通用开发平台,由 Microsoft 和 GitHub 上的 .NET 社区...
首先插件配备好了,写一个HTML测试一下 首先创建一个文件夹,创建一个HTML 文件...
IT之家2月18日消息外媒 Windows Latest 报道,微软正在与谷歌合作进行一项新的改...
第一课趣味二进制——修改植物大战僵尸数据 任务介绍 学习目标 知识需求 需求工...
昨天刚学了html的一些内容,就迫不及待的想做个京东上面的搜索条,结果做是做出...
1.ajax跨域传递值是所需要的回传的类型为jsonp $.ajax({url: "http://.......",t...
2 月 18 日消息 据外媒 Windowslatest 报道,在预览版本中发现的参考资料表明,...