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.& ...
随机推荐
- Python实现文件阅读功能(Python学习笔记)
#!/usr/bin/python# Filename: filereader.pyimport sys def readfile(filename): '''Print a file to the ...
- php函数: call_user_func()和call_user_func_array() 使用详解
call_user_func 该函数允许直接调用自己写的函数,可以直接传入一些参数. 使用方法1:给自己写的函数传入参数,一个特别的调用函数的方法. <?php funciotn test1($ ...
- 【agc004f】Namori Grundy
那个问一下有人可以解释以下这个做法嘛,看不太懂QwQ~ Description 有一个n个点n条边的有向图,点的编号为从1到n. 给出一个数组p,表明有(p1,1),(p2,2),…,(pn,n)这n ...
- iOS下调用元素的focus方法,input元素不聚焦,键盘不弹起的问题
页面元素 <input type="text" ref="elInput"/> <div style="margin-top:20p ...
- websocket调试工具
http://www.blue-zero.com/WebSocket/ wss://yy.xxx.com/video/websocket/client.ws
- COGS——T 21. [HAOI2005] 希望小学
http://www.cogs.pro/cogs/problem/problem.php?pid=21 ★★ 输入文件:hopeschool.in 输出文件:hopeschool.out ...
- jquery快速清除复选框、单选框的选中
$(":checked").attr("checked", "");
- ArcGIS api for javascript——显示多个查询结果
描述 本例展示了在重叠的多边形处理查询的一种方式.单击一个石油和天然气的字段来查看地图上的高亮显示.如果仅仅点击一个要素,能够在单击一次来查看包含一些属性的InfoWindow.如果偶然单击到重叠的要 ...
- Use Uncertainty As a Driver
 Use Uncertainty As a Driver Kevlin Henney ConFRonTEd WiTH TWo opTionS, most people think that the ...
- ztree中依据后台中传过来的node的id,将这个node的复选框置为不可用
var treeObj = $.fn.zTree.getZTreeObj("treeDemo");//树对象 var node = treeObj.getNodeByParam(& ...