这篇我们就用实例来看看我们在代码中如何使用Fragment

一:静态添加Fragment

新建一个项目,添加两个Fragment的布局文件fragment_title,fragment_content

<?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="#44444433"
android:orientation="vertical"
android:gravity="center"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是微信"/> </LinearLayout>
<?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="#44994433"
android:orientation="vertical"
android:gravity="center"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是Fragment内容"/> </LinearLayout>

然后创建两个class继承自Fragment,这里面导入的包是android.app.Fragment,而不是V4包,对于这两个包的区别后面我会贴出。

package com.jkxy.fragmentdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; /**
* Created by cuishuang on 16/7/29.
*/
public class TitleFragment extends Fragment { @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_title,container,false);
} }
package com.jkxy.fragmentdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; /**
* Created by cuishuang on 16/7/29.
*/
public class ContentFragment extends Fragment { @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_content,container,false);
}
}

最后是MainActivity,这里面没加其他代码这里就不在贴出了

运行效果:

二:动态添加Fragment

你已经学会了如何在XML中使用Fragment,但是这仅仅是Fragment最简单的功能而已。Fragment真正的强大之处在于可以动态地添加到Activity当中,因此这也是你必须要掌握的东西。当你学会了在程序运行时向Activity添加Fragment,程序的界面就可以定制的更加多样化。下面我们立刻来看看,如何动态添加Fragment。

还是在上一节代码的基础上修改,打开activity_main.xml,将其中代码全部删除,改成下面的样子:

<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.jkxy.fragmentdemo.MainActivity"> <Button
android:id="@+id/btn_fragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显示第一个Fragment"/>
<Button
android:id="@+id/btn_fragment2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显示第二个Fragment"/> <FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/> </LinearLayout>

主界面上有两个按钮和一个FrameLayout布局。这两个按钮分别用来在这个FrameLayout加载Fragment1和Fragment2的实例。效果如下:

其它代码都没有动,主要的是在MainActivity里,点击这两个按钮时做的处理:

package com.jkxy.fragmentdemo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View; public class MainActivity extends FragmentActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} public void initView(){
findViewById(R.id.btn_fragment1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment1 frgment1 = new Fragment1();
transaction.add(R.id.fragment_container,frgment1);
transaction.commit(); }
}); findViewById(R.id.btn_fragment2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment2 frgment2 = new Fragment2();
transaction.add(R.id.fragment_container,frgment2);
transaction.commit();
}
}); }
}

看上面的代码很容易明白,在点击按钮时都做了类似的操作:

FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment2 frgment2 = new Fragment2();
transaction.add(R.id.fragment_container,frgment2);
transaction.commit();

动态添加Fragment主要分为4步:

  • 1.获取到FragmentManager,在V4包中通过getSupportFragmentManager,在系统中原生的Fragment是通过getFragmentManager获得的。
  • 2.开启一个事务,通过调用beginTransaction方法开启。
  • 3.向容器内加入Fragment,一般使用add或者replace方法实现,需要传入容器的id和Fragment的实例。
  • 4.提交事务,调用commit方法提交。

app包中的fragment和v4包中的fragment的使用的区别

1、尽量不要用app包中的fragment,因为这个是在3.0之后才有的,支持的版本太高,在低版本中是是用不了的

2、android.support.v4.app.Fragment:可以兼容到1.6的版本,

3、关于这两个fragment使用<fragment>标签的问题
 (1)app.fragment和v4.fragment都是可以使用<fragment>标签的
      只是在在使用的时候如果是app.fragment则没有什么特殊的地方继承Activity即可。

(2)当v4.fragment使用<fragment>标签的时候就要特别注意了:
  当这个Activity的布局中有<fragment>标签的时候,这个Activity必须继承
  FragmentActivity,否则就会报错

08-27 08:25:04.946: E/AndroidRuntime(9839): Caused by: java.lang.ClassCastException: com.example.android_fragment_bottom.fragments.TopBarFragment cannot be cast to android.app.Fragment

此时如果不卜继成FragmentActivity的话 编译系统会把<fragment>认为是app包中的Fragment来处理。但是此时我们导入的是v4包中的Fragment

Android官方文档中的Fragment的例子就是以app包中的Fragment来讲解的。

(3)app包中关于Fragment的类和方法在V4包中都是有相应的对应的

Fragment-两种使用方式的更多相关文章

  1. Android中Fragment与Activity之间的交互(两种实现方式)

    (未给Fragment的布局设置BackGound) 之前关于Android中Fragment的概念以及创建方式,我专门写了一篇博文<Android中Fragment的两种创建方式>,就如 ...

  2. Android 常用UI控件之TabHost(1)TabHost的两种布局方式

    TabHost是Android中的tab组件. TabHost布局文件的基本结构 TabHost下有个layout,这个layout中有TabWidget与FrameLayout.TabWidget是 ...

  3. Web APi之认证(Authentication)两种实现方式【二】(十三)

    前言 上一节我们详细讲解了认证及其基本信息,这一节我们通过两种不同方式来实现认证,并且分析如何合理的利用这两种方式,文中涉及到的基础知识,请参看上一篇文中,就不再叙述废话. 序言 对于所谓的认证说到底 ...

  4. Android中BroadcastReceiver的两种注册方式(静态和动态)详解

    今天我们一起来探讨下安卓中BroadcastReceiver组件以及详细分析下它的两种注册方式. BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来 ...

  5. JavaScript 函数的两种声明方式

    1.函数声明的方式 JavaScript声明函数有两种选择:函数声明法,表达式定义法. 函数声明法 function sum (num1 ,num2){ return num1+num2 } 表达式定 ...

  6. Redis两种持久化方式(RDB&AOF)

    爬虫和转载请注明原文地址;博客园蜗牛:http://www.cnblogs.com/tdws/p/5754706.html Redis所需内存 超过可用内存怎么办 Redis修改数据多线程并发—Red ...

  7. struts2+spring的两种整合方式

    也许有些人会因为学习了struts1,会以为struts2.struts1与spring的整合也是一样的,其实这两者相差甚远.下面就来讲解一下struts2与spring的整合两种方案.(部分转载,里 ...

  8. easyui datagride 两种查询方式

    easyui datagride 两种查询方式function doReseach() { //$('#tt').datagrid('load', { // FixedCompany: $('.c_s ...

  9. 【Visual Lisp】两种出错处理方式

    两种出错处理方式:一种是对出错函数进行重定义,一种是对错误进行捕捉处理. ;;============================================================= ...

  10. 两种include方式及filter中的dispatcher解析

    两种include方式 我自己写了一个original.jsp,另外有一个includedPage.jsp,我想在original.jsp中把includedPage.jsp引进来有两种方式: 1.& ...

随机推荐

  1. 最简单的DES加密算法实现

    Base64.java package com.mstf.des; import java.io.UnsupportedEncodingException; /** * base64编码/解码 * @ ...

  2. ios下微信浏览器如何唤醒app?app已上架应用宝

    android下可以通过在应用宝微下载地址后面加参数&android_schema='应用schema'来实现,ios下如何实现? ios下微信浏览器如何唤醒app?app已上架应用宝 > ...

  3. sql索引碎片产生的原理 解决碎片的办法(sql碎片整理)

    本文讲述了SQL SERVER中碎片产生的原理,内部碎片和外部碎片的概念.以及解决碎片的办法和填充因子.在数据库中,往往每一个对于某一方面性能增加的功能也会伴随着另一方面性能的减弱.系统的学习数据库知 ...

  4. AIX系统谨慎使用reboot命令

    在客户一次停机维护中,发现了这个问题. 环境是ORACLE 10G RAC for AIX6,使用了HACMP管理共享磁盘. 在停机维护时间段内需要重启主机,当关闭了数据库和CLUSTER后,节点1使 ...

  5. Linux LVM在线扩容

    环境: 虚拟化环境,SUSE Linux Enterprise Server 11sp3,直接把虚拟磁盘从100G改成150G. 现有的LVM是100G,/home 的LV需要再加50G. 步骤: f ...

  6. Laravel+vue实现history模式URL可行方案

    项目:laravel + vue 实现前后端分离.vue-router 默认 hash 模式 -- 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载. h ...

  7. Android SDK Manager代理设置

    1.SDK Manager中打开 Tools—>Manage Add-on Sites…—>User Defined Sites 2.New …输入: http://android-mir ...

  8. ArcGIS api for javascript——查找任务-在地图上查找要素

    描述 本例展示了如何使用查找任务搜索数据.本例在地图上用图表显示结果并用DojoX的grid格式化结果为表格样式. FindTask构造函数需要一个ArcGIS Server地图服务的URL.本例使用 ...

  9. Servlet具体解释

    Servlet具体解释 基本概述 Session在计算机中,尤其是在网络应用中,称为"会话控制".在计算机专业术语中.Session是指一个终端用户与交互系统进行通信的时间间隔,通 ...

  10. NGINX 代理以及 HTTPS (一)

    一. Nginx 安装 和基础代理配置 假如 启动nginx 出现这个错误,可能是 iis服务被打开了,80端口被占用了. 需要如下操作: 用Nginx 配置一个test.com 的代理名称.配置ho ...