这篇我们就用实例来看看我们在代码中如何使用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. iview中键盘上下左右事件的方法

    document.addEventListener('keydown', function(e){ var keyCode = e.keyCode; // Esc slide-up ) { e.pre ...

  2. Decorator - 利用装饰器武装前端代码

    历史 以前做后端时,接触过一点Spring,也是第一次了解DI.IOC等概念,面向切面编程,对于面向对象编程还不怎么熟练的情况下,整个人慌的一批,它的日志记录.数据库配置等都非常方便,不回侵入到业务代 ...

  3. echarts 初始化失败问题。

    dom 实例容器,一般是一个具有高宽的div元素. 注:如果div是隐藏的,ECharts 可能会获取不到div的高宽导致初始化失败,这时候可以明确指定div的style.width和style.he ...

  4. #ifdef__cplusplus

    百度知道: 一般用于将C++代码以标准C形式输出(即以C的形式被调用),这是因为C++虽然常被认为是C的超集,但是C++的编译器还是与C的编译器不同的.C中调用C++中的代码这样定义会是安全的. 一般 ...

  5. XWIKI的搭建

    原文地址:https://my.oschina.net/gywbest/blog/780569 一 应用背景描述 在平时的运维工作中,把常规工作进行文档整理非常重要,无论是平时工作处理或是工作交接,实 ...

  6. 洛谷 P1176 路径计数2

    P1176 路径计数2 题目描述 一个N×N的网格,你一开始在(1, 1),即左上角.每次只能移动到下方相邻的格子或者右方相邻的格子,问到达(N, N),即右下角有多少种方法. 但是这个问题太简单了, ...

  7. CF 558A(Lala Land and Apple Trees-暴力)

    A. Lala Land and Apple Trees time limit per test 1 second memory limit per test 256 megabytes input ...

  8. 使用ssh过程中对数据库进行update时报错

    报错信息:org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in ...

  9. PIO Core

    PIO核概述 具有Avalon接口的并行输入/输出(parallel input/output - PIO)核,在Avalon存储器映射(Avalon Memory-Mapped Avalon-MM) ...

  10. 学习 shell —— 创建序列数组

    list/array 1. seq 方法创建 基本用法: $ a_num_seq = ($seq 5) $ echo $a_num_seq 1 2 3 4 5 a_num_seq 得到是字符串,不同之 ...