Android应用开发中Fragment的静态加载与动态加载实例
作者:高杰才_Android 发布时间:2021-11-14 15:14:11
1、Fragment的静态使用
Fragment是作为Activity的UI的一部分,它内嵌在Activity中,多个Fragment可以把一个Activity分成多个部分,这在大屏幕手机或者平板电脑中会比较多的用到,这样就不用使用多个Activity来切换这么麻烦了。当然Fragment也可以不显示,只在后台处理一些数据,这篇文章中就暂时不谈到这个。以下来看怎么静态地在Activity的布局文件中添加Fragment.
自定义的Fragment通常要继承Fragment这个类,也有一些特殊的是继承ListFragment,DialogFragment等。继承Fragment类通常要实现三个方法:onCreate(), onCreateView(), onPause();
我在Activity中定义了两个Fragment,一个是放在左边的LeftFragment,一个是放在右边的RightFragment.以下是代码:首先我们要实现自己的Fragment类
LeftFragment类:
public class LeftFragment extends Fragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
System.out.println("LeftFragment onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
System.out.println("LeftFragment onCreateView");
// 第一个参数是这个Fragment将要显示的界面布局,第二个参数是这个Fragment所属的Activity,第三个参数是决定此fragment是否附属于Activity
return inflater.inflate(R.layout.leftfragment, container, true);
}
@Override
public void onResume()
{
super.onResume();
System.out.println("LeftFragment onResume");
}
@Override
public void onPause()
{
super.onPause();
System.out.println("LeftFragment onPause");
}
@Override
public void onStop()
{
super.onStop();
System.out.println("LeftFragment onStop");
}
}
这里实现了几种回调函数,主要是为了看清Activity和Fragment生命周期之间的关系.其中onCreateView()方法是将本Fragment对应的布局返回给Activity的布局,让Activity进行加载. inflater.inflate(R.layout.leftfragment, container, true)方法中的第一个参数R.layout.leftfragment是这个Fragment对应的布局文件ID, 第二个参数container是要插入的目标Activity, 第三个参数是决定这个Fragment是否依附于这个container.
LeftFragment对应的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_orange_dark"
android:orientation="vertical" >
<Button
android:id="@+id/previous_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/previous_button" />
<Button
android:id="@+id/next_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/next_button" />
<Button
android:id="@+id/exit_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/exit_button" />
</LinearLayout>
RightFragment类:和LeftFragment类似
public class RightFragment extends Fragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
System.out.println("RightFragment onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
System.out.println("RightFragment onCreateView");
return inflater.inflate(R.layout.rightfragment, container, true);
}
@Override
public void onResume()
{
super.onResume();
System.out.println("RightFragment onResume");
}
@Override
public void onPause()
{
super.onPause();
System.out.println("RightFragment onPause");
}
@Override
public void onStop()
{
super.onStop();
System.out.println("RightFragment onStop");
}
}
RightFragment对应的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/show_message"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/holo_blue_dark"
android:text="@string/show_message" />
</LinearLayout>
最后是Activity的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<fragment
android:id="@+id/left_fragment"
android:name="com.sunflower.LeftFragment"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="3" />
<fragment
android:id="@+id/right_fragment"
android:name="com.sunflower.RightFragment"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
在Activity中的布局文件中加入Fragment标签,其中android:name属性对应的就是自定义Fragment类的全名,系统会根据这个调用指定的Fragment的onCreateView()方法来得到这个Fragment的布局,然后加入Activity中. onCreateView()方法中的Container参数就是这时候传递过去的。
看看显示结果:
打开程序时生命周期显示:
按返回键时生命周期显示:
2、动态地使用Fragment
上面已经演示了最简单的使用Fragment的方式,下面分享一下如何动态的添加、更新、以及删除Fragment。
首先是,MainActivity的布局文件activity_main.xml,该文件布局文件上面的顶部是一个TitleFragment,是一个静态声明的Fragment。
中间也是一个Fragment,但是这个Fragment是动态使用的。
最下面是四个按钮。用include标签包含外部的布局文件进来的。
<RelativeLayout 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" >
<fragment
android:id="@+id/id_fragment_title"
android:name="com.example.dynamicfragment.TitleFragment"
android:layout_width="fill_parent"
android:layout_height="45dp" />
<include
android:id="@+id/id_ly_bottombar"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
layout="@layout/bottombar" />
<FrameLayout
android:id="@+id/id_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/id_ly_bottombar"
android:layout_below="@id/id_fragment_title" />
</RelativeLayout>
然后是,MainActivity.java文件。也是我们这个demo当中最重要的代码文件,首先是将上面的布局文件通过setContentView()加载进来.然后是通过setDefaultFragment();将默认的ContentFragment动态的加载进来。接下来就是通过我们在最下面防止的四个按钮可以随意的动态切换Fragment。这也是为什么Fragment会有如此火的原因吧~~~^^
public class MainActivity extends ActionBarActivity implements OnClickListener {
private ImageButton mTabWeixin;
private ImageButton mTabFriend;
private ImageButton mTabDiscover;
private ImageButton mTabMe;
private ContentFragment mWeiXinFragment;
private FriendFragment mFriendFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initView();
}
public void initView() {
// 初始化控件和声明事件
mTabWeixin = (ImageButton) findViewById(R.id.weixin);
mTabFriend = (ImageButton) findViewById(R.id.friend);
mTabWeixin.setOnClickListener(this);
mTabFriend.setOnClickListener(this);
// 设置默认的Fragment
setDefaultFragment();
}
@SuppressLint("NewApi")
private void setDefaultFragment() {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
mWeiXinFragment = new ContentFragment();
transaction.replace(R.id.id_content, mWeiXinFragment);
transaction.commit();
}
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
// 开启Fragment事务
FragmentTransaction transaction = fm.beginTransaction();
switch (v.getId()) {
case R.id.weixin:
if (mWeiXinFragment == null) {
mWeiXinFragment = new ContentFragment();
}
// 使用当前Fragment的布局替代id_content的控件
transaction.replace(R.id.id_content, mWeiXinFragment);
break;
case R.id.friend:
if (mFriendFragment == null) {
mFriendFragment = new FriendFragment();
}
transaction.replace(R.id.id_content, mFriendFragment);
break;
}
// transaction.addToBackStack();
// 事务提交
transaction.commit();
}
}
从上面的代码,我们可以看出,我们可以使用FragmentManager对Fragment进行动态的加载,这里使用的replace方法~~~下一节我们会详细的介绍FragmentManager的常用API。。。。^^
注:如果使用android3.0一下的版本,需要引入v4的包,然后Activity继承FragmentActivity,然后通过getSupportFragmentManager()获得FragmentManager对象,不过还是建议把Menifest文件的uses-sdk的minSdkVersion和targetSdkVersion都改为11以上,这样就不必引入v4的包了。
代码的中间有俩个动态加载进来的Fragment,这个和静态使用Fragment的声明方式是一样的,写一个继承Fragment的类,然后设置相应的布局,由于时间的关系,我这里只写了俩个Fragment,现在把这俩个的代码页贴出来:
第一个Fragment和他相应的布局文件:
public class ContentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_content, container, false);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="weixin"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
第二个Fragment和他相应的布局文件:
public class FriendFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_friend, container, false);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="friend"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
好了,现在基本的代码都有了,我们把demo的运行图贴出来给大家分享一下(注:时间原因,没注意布局以及图片的美化,只是功能的实现),这是分别点击下面第一个和第二个按钮的效果图,从而实现了中间用一个Fragment动态的加载这俩个Fragment的显示。
ps:为了代码的简洁,就不添加按钮的点击变化什么的了,主要讲解功能了~~~


猜你喜欢
- 对象的初始化和清理生活中我们买的电子产品都基本会有出厂设置,在某一天我们不用时候也会删除一些自己信息数据保证安全。C++中的面向对象来源于生
- 网上有很多关于拍照上传的实现方法,如果用新版本android去运行有可能会发现根本实现不了。主要原因是android从4.4版本开始通过in
- Spring容器可以在不使用<constructor-arg>和<property>元素的情况下自动装配相互协作的b
- 本文实例讲述了Java单例模式。分享给大家供大家参考,具体如下:在实际开发的时候会有一些需求,在某个类中只能允许同时存在一个对象。这时就需要
- 常量,顾名思义,就是“不会改变的量”。我们平时书写的数字(比如12.85)、字符(比如'F')、字符串(比如"谢谢
- MongoDB的基本使用添加依赖<dependency>
- 关于静态类型检查和动态类型检查的解释:静态类型检查:基于程序的源代码来验证类型安全的过程;动态类型检查:在程序运行期间验证类型安全的过程;J
- 本文实例讲述了android同时控制EditText输入字符个数和禁止特殊字符输入的方法。分享给大家供大家参考。具体分析如下:这里总结了三种
- 工作中因业务需求,将数据库中的树状结构的数据根据父节点获取所有的子节点实现思路1.获取整个数据的list集合数据2.将数据分组,java8
- 在Android上,不止一个途径来侦听用户和应用程序之间交互的事件。对于用户界面里的事件,侦听方法就是从与用户交互的特定视图对象截获这些事件
- 可以使用 Intent.createChooser() 的方法来创建 Intent,并传入想要的 Sting 作为标题。 以wallpape
- 我们在编写网络程序的时候,经常会进行如下操作:申请一个缓冲区从数据源中读入数据至缓冲区解析缓冲区的数据重复第2步表面上看来这是一个很常规而简
- SpringMVC异常处理机制(一)项目前准备首先参照文章Spring课程工程构建+SpringMVC简介及其快速入门搭建项目搭建好一个项目
- 一、反射的基本概念1、反射的概念将类的各个组成部分封装成其他对象,这就是反射的机制.通过上图,我们可以通过反射获得Person类的Class
- /*最小树形图图模版-朱刘算法模版说明:点标号必须0-(N-1) 必须去除到自身的点(到自身的边的边权赋无限大)*/
- redissonredisson 实现分布式锁的机制如下:依赖版本implementation 'org.redisson:redi
- 前面我们已经学习了平时实际开发中用得较多的线性布局(LinearLayout)与相对布局(RelativeLayout), 其实学完这两个基
- 前言本文主要是将最近工作中遇到的一个问题进行总结分享,主要介绍的是如何让WebView中H5页面全屏播放视频。关于这个问题,做一下简单分析,
- 求一个n阶行列式,一个比较简单的方法就是使用全排列的方法,那么简述以下全排列算法的递归实现。首先举一个简单的例子说明算法的原理,既然是递归,
- 多网卡环境下Eureka服务注册IP选择问题场景服务器上分别配置了eth0和eth1两块网卡,只有eth1的地址可供其它机器访问,在这种情况