Fragment-两种使用方式
这篇我们就用实例来看看我们在代码中如何使用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-两种使用方式的更多相关文章
- Android中Fragment与Activity之间的交互(两种实现方式)
(未给Fragment的布局设置BackGound) 之前关于Android中Fragment的概念以及创建方式,我专门写了一篇博文<Android中Fragment的两种创建方式>,就如 ...
- Android 常用UI控件之TabHost(1)TabHost的两种布局方式
TabHost是Android中的tab组件. TabHost布局文件的基本结构 TabHost下有个layout,这个layout中有TabWidget与FrameLayout.TabWidget是 ...
- Web APi之认证(Authentication)两种实现方式【二】(十三)
前言 上一节我们详细讲解了认证及其基本信息,这一节我们通过两种不同方式来实现认证,并且分析如何合理的利用这两种方式,文中涉及到的基础知识,请参看上一篇文中,就不再叙述废话. 序言 对于所谓的认证说到底 ...
- Android中BroadcastReceiver的两种注册方式(静态和动态)详解
今天我们一起来探讨下安卓中BroadcastReceiver组件以及详细分析下它的两种注册方式. BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来 ...
- JavaScript 函数的两种声明方式
1.函数声明的方式 JavaScript声明函数有两种选择:函数声明法,表达式定义法. 函数声明法 function sum (num1 ,num2){ return num1+num2 } 表达式定 ...
- Redis两种持久化方式(RDB&AOF)
爬虫和转载请注明原文地址;博客园蜗牛:http://www.cnblogs.com/tdws/p/5754706.html Redis所需内存 超过可用内存怎么办 Redis修改数据多线程并发—Red ...
- struts2+spring的两种整合方式
也许有些人会因为学习了struts1,会以为struts2.struts1与spring的整合也是一样的,其实这两者相差甚远.下面就来讲解一下struts2与spring的整合两种方案.(部分转载,里 ...
- easyui datagride 两种查询方式
easyui datagride 两种查询方式function doReseach() { //$('#tt').datagrid('load', { // FixedCompany: $('.c_s ...
- 【Visual Lisp】两种出错处理方式
两种出错处理方式:一种是对出错函数进行重定义,一种是对错误进行捕捉处理. ;;============================================================= ...
- 两种include方式及filter中的dispatcher解析
两种include方式 我自己写了一个original.jsp,另外有一个includedPage.jsp,我想在original.jsp中把includedPage.jsp引进来有两种方式: 1.& ...
随机推荐
- c# 枚举enum
1 定义枚举 enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; 默认情况下,枚举中的每个元素的 ...
- Hyper-V 导入与导出虚拟机
虚拟机的导入与导出功能可以将虚拟机通过文件的方式进行转移,可以将虚拟机的文件复制到活动硬盘,然后带到其他的地点进行导入,这样方便了虚拟机的跨地域的转移.但是有一点要注意,所有要转移的虚拟机都必须处于停 ...
- javascript--记忆函数
function memory(val) { if(!memory.cached) {//判断是否创建了缓存 memory.cached = {}; } if(memory.cached[val] ! ...
- Rman备份异机恢复
最后更新时间:2018/12/29 前置条件 已准备一台安装好Centos6+oracle11gr2 软件的服务器; 只安装了 oracle 数据库软件,需要手工创建以下目录: #环境变量 expor ...
- perl模块
查看perl模块安装目录:find `perl -e ‘print “@INC”‘` -name ‘*.pm’ -print 为什么要写或要模块呢?简言之:代码重用,更多见于写一组工具集,有很多地方是 ...
- CF17E Palisection(回文树)
题意翻译 给定一个长度为n的小写字母串.问你有多少对相交的回文子 串(包含也算相交) . 输入格式 第一行是字符串长度n(1<=n<=2*10^6),第二行字符串 输出格式 相交的回文子串 ...
- 【ICM Technex 2018 and Codeforces Round #463 (Div. 1 + Div. 2, combined) D】Tree
[链接] 我是链接,点我呀:) [题意] 让你在树上找一个序列. 这个序列中a[1]=R 然后a[2],a[3]..a[d]它们满足a[2]是a[1]的祖先,a[3]是a[2]的祖先... 且w[a[ ...
- rac重新启动遭遇ORA-01078、ORA-01565、ORA-17503、ORA-12547
今天測试环境server重新启动导致一个节点集群无法重新启动,遭遇ORA-12547错误.详细例如以下: server重新启动后,rac1集群无法启动,rac2正常启动: [root@rac1 ~]# ...
- 仿小米简约Calculator
上个星期的时候,我想教我朋友做一个简单的app.想来想去教什么比較好.当时看见小米的计算器认为比較美丽,就想这个简单.然后就開始动手做了.我以为能够一个小时能够搞定.没想到花了快一天的时间. 哎.突然 ...
- 跨域post 及 使用token防止csrf 攻击
环境: 后台使用的python - flask 前台使用angular框架 1.一个跨域post的样例: 跨域post有多种实现方式: 1.CORS:http://blog.csdn.net/hfah ...