Fragment通俗来讲就是碎片,不能单独存在,意思就是说必须依附于Activity,一般来说有两种方式把Fragment加到Activity,分为静态,动态。

静态即为右键单击,建立一个Fragment,选择Blank,在Activity布局中直接加fragment,name属性直接指向之前建立的Fragment,这就添加上了Fragment,这种较为简单。

动态:

我们要做的是在Activity中添加一个Fragment,Fragment中有两个按钮,当按下按钮时分别切换不同的Fragment,注意,切换不同的Fragment的代码在Activity中写。

实现Fragment和Activity之间的通信,步骤一般分为五步,1、在Fragment中声明一个接口。 2、在Activity中实现在Fragment中声明的接口。

3、在Fragment中声明一个接口对象。 4、在Fragment的生命周期中onAttach方法中判断当前Activity是否实现了此Fragment中声明的接口

5、调用Activity中实现的方法 (接口对象.方法名)

首先,建立一个名为OneFragment的Fragment,在右键单击建立时勾选Include fragment factory methods 和Include interface callback,这样会自动添加相关代码,省掉很多时间.再在新建立的Fragment里添加两个按钮,设置Id。

布局代码如下

<FrameLayout 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"
tools:context="com.example.administrator.homeworepar.Fragment.OneFragment"> <!-- TODO: Update blank fragment layout -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt1"
android:text="好友"/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt2"
android:text="消息"
android:layout_gravity="center_horizontal|top" /> </FrameLayout> 下面为Fragment的代码
package com.example.administrator.homeworepar.Fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button; import com.example.administrator.homeworepar.R; /**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OneFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link OneFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class OneFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters
private String mParam1;
private String mParam2; private OnFragmentInteractionListener mListener; public OneFragment() {
// Required empty public constructor
} /**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment OneFragment.
*/
// TODO: Rename and change types and number of parameters
public static OneFragment newInstance(String param1, String param2) {
OneFragment fragment = new OneFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
} @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_one, container, false);
Button bt1= (Button) view.findViewById(R.id.bt1); // 实现的功能是的那个按下按钮时,会调用ACtivity中的changFragment方法
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.changFragment(1);
}
});
Button bt2= (Button) view.findViewById(R.id.bt2);
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.changFragment(2);
}
});
return view;
} @Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) { 判断是否实现了接口,如果实现了接 口,就把Activity转换为接口的对 象,这样就可以调用方 法
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
} @Override
public void onDetach() {
super.onDetach();
mListener = null;
} /**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener { // 此段为自动添加的接口,在接口中实现一个方法修改完后会有其他代码出错,只要 把出错代码删掉即可。
// TODO: Update argument type and name
void changFragment(int which);
}
 

再建立一个Activity,

package com.example.administrator.homeworepar.Fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity; import com.example.administrator.homeworepar.R; public class Fragment2Activity extends AppCompatActivity implements OneFragment.OnFragmentInteractionListener { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment2);
}
@Override
public void changFragment(int which) {
if(which==1){
Fragment fragment1=new BlankFragment(); //实现Fragment中的方法,当得到的值为1时,把BlankFragment填充 //到Id为fl2中的FrameLayout中,
getSupportFragmentManager()
                    .beginTransaction().replace(R.id.fl2,fragment1).commit();
}else if(which==2){
Fragment fragment2=new SecondFragment();
getSupportFragmentManager()
.beginTransaction().replace(R.id.fl2,fragment2).commit();
}
}
} ACtivity布局代码如下
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.homeworepar.Fragment.Fragment2Activity">
<fragment
android:layout_width="match_parent"
android:layout_height="50dp"
android:name="com.example.administrator.homeworepar.Fragment.OneFragment"
android:id="@+id/fragment3" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fl2"
android:layout_below="@+id/fragment3"> </FrameLayout>
</RelativeLayout>
这样就可以实现ACtivity与Fragment间的通信,另外Fragment还有和Activity一样还有生命周期的问题

方法名 说明
onAttach () Fragment被附加到Activity的时,调用此函数,在这个方法中可以获得宿主Activity。
onCreate () Fragment被创建的时,调用此函数。
onCreateView () Fragment的布局加载时,调用此函数。
onActivityCreated () 当宿主Activity启动完毕后,调用此函数。
onStart () 启动Fragment时,调用此函数。
onResume () Fragment恢复时,调用此函数。
onPause () Fragment暂停时,调用此函数。
onStop() Fragment停止时,调用此函数。
onDestroyView() 销毁Fragment中的View控件时,调用此函数。
onDestroy() 销毁Fragment时,调用此函数。
onDetach() Fragment从Activity脱离时,调用此函数

 

Fragment的生命周期和Activity之间的通信以及使用的更多相关文章

  1. 【Android 应用开发】Activity生命周期 与 Activity 之间的通信

    一. Activity生命周期 上图 1. Activity状态 激活状态 : Activity出于前台 , 栈顶位置; 暂停状态 : 失去了焦点 , 但是用户仍然可以看到 , 比如弹出一个对话框 , ...

  2. Activity生命周期 与 Activity 之间的通信

    一. Activity生命周期 上图 1. Activity状态 激活状态 : Activity出于前台 , 栈顶位置; 暂停状态 : 失去了焦点 , 但是用户仍然可以看到 , 比如弹出一个对话框 , ...

  3. Fragment的生命周期&同一Activity下不同Fragment之间的通信

    Android开发:碎片Fragment完全解析(2) Fragment的生命周期 和Activity一样,Fragment也有自己的生命周期,理解Fragment的生命周期非常重要,我们通过代码的方 ...

  4. java之线程(线程的创建方式、java中的Thread类、线程的同步、线程的生命周期、线程之间的通信)

    CPU:10核 主频100MHz 1核  主频    3GHz 那么哪一个CPU比较好呢? CPU核不是越多越好吗?并不一定.主频用于衡量GPU处理速度的快慢,举个例子10头牛运送货物快还是1架飞机运 ...

  5. Android成长日记-Fragment的生命周期与Activity通信

    1. public void onAttach(Activity activity) 当Fragment被添加到Activity时候会回调这个方法,并且这个方法只会被回调一次 2. public vo ...

  6. Fragment的生命周期和activity如何的一个关系

  7. fragment的生命周期及其各个周期方法的作用

    先上生命周期图: Fragment的生命周期图: 与Activity的生命周期对比图: 由于Fragment是嵌在Activity中使用的,故其生命周期也是依赖于Activity的周期的,或者说Fra ...

  8. Activity与Fragment的生命周期

    今天看到一张图,详细描述了Activity和Fragment的生命周期,好资源共享咯!

  9. Activity与Fragment的生命周期详解

    在安卓中Activity与Fragment是非常相似的两个类,它们各自都拥有自己的生命周期,且都可以用来显示布局文件中的视图.其中Activity是通过setContenView()显示视图,而Fra ...

随机推荐

  1. ASP.NET MVC 4 RC的JS/CSS打包压缩功能 (转载)

    ASP.NET MVC 4 RC的JS/CSS打包压缩功能 打包(Bundling)及压缩(Minification)指的是将多个js文件或css文件打包成单一文件并压缩的做法,如此可减少浏览器需下载 ...

  2. 【转】win7 虚拟机virtualbox中ubuntu12.04安装samba实现文件共享

    原文网址:http://blog.csdn.net/watkinsong/article/details/8878786 昨天心血来潮,又装了个虚拟机,然后安装了ubuntu12.04,为了实现在虚拟 ...

  3. HDOJ -- 4632 区间DP

    Palindrome subsequence Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65535 K (Java/ ...

  4. WebSocket学习笔记IE,IOS,Android等设备的兼容性问

    WebSocket学习笔记IE,IOS,Android等设备的兼容性问 一.背景 公司最近准备将一套产品放到Andriod和IOS上面去,为了统一应用的开发方式,决定用各平台APP嵌套一个HTML5浏 ...

  5. Bzoj 3694: 最短路 树链剖分

    3694: 最短路 Time Limit: 5 Sec  Memory Limit: 256 MBSubmit: 67  Solved: 34[Submit][Status][Discuss] Des ...

  6. 《Linear Algebra and Its Applications》-chaper1-线性方程组- 线性变换

    两个定理非常的简单显然,似乎是在证明矩阵代数中的基本运算律.但是它为后面用“线性变换”理解矩阵-向量积Ax奠定了理论基础. 结合之前我们讨论过的矩阵和向量的积Ax的性质,下面我们就可以引入线性变换了. ...

  7. 打印从1到k之间的所有素数

    问题分析:素数是指大于1且只能被它本身和1整除的数,根据定义可以从2开始对一个数取余数一直到它本身,若它有第三个整除数,则可以判定它不是素数.若使用这种方法,会浪费时间,我们可以判断2到这个数的算术平 ...

  8. openSuSE12.1 zypper LAMP

    LAMP是由Apache MySQL PHP组成的,是在Linux下最受欢迎的软件组合之一,目前互联网上有很多网站运行在LAMP服务器上. Linux - 是富有情味的开源操作系统:Apache -  ...

  9. cat、cp命令

    cat是查看文件内容, cp –cp是连目录及件文件都拷贝 cp是拷贝文件 a.txt里的内容是, abc def ghi cat a.txt |grep –v ghi 得到结果, abc def h ...

  10. hdoj 1827 Summer Holiday【强连通分量&&缩点】

    Summer Holiday Time Limit: 10000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)T ...