我个人将Fragment与Activity间的通信比喻为JSP与Servlet间的通信,fragment中用接口的方式来进行与Activity的通信。通信的结果可以作为数据传入另一个Fragment中。当然两个Fragment之间也是可以进行通信的~

注意加载或者切换Fragment时,必须new一个FragmentTransaction对象,不能用同一个FragmentTransaction对象进行对容器进行替换、增加fragment。将fragment填充进容器的方式是(这里分别给两个容器填充了两个fragment对象):

     FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction(); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.add(R.id.container_fragment, new MyFragment())
.commit(); //不能用同个FragmentTransaction来加载两个fragment
fragmentManager.beginTransaction()
.add(R.id.container_fragment02, new MyFragment02())
.commit();

更换fragment的方式是:

        getSupportFragmentManager().beginTransaction().
replace(R.id.container_fragment02, fragment)
.addToBackStack(null)
.commit();

  本实例完成的是点击一个Fragment中的按钮后,fragment给activity传值,activity接受到值后给另一个fragment(右边的)传值,以此改变textview中的内容。

activity_main.xml (定义了2个布局来作为fragment的容器)

<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:background="#000000"
android:orientation="horizontal" > <FrameLayout
android:id="@+id/container_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ffffff"
android:layout_marginRight="1dp" /> <FrameLayout
android:id="@+id/container_fragment02"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ffffff"
android:layout_marginLeft="1dp" >
</FrameLayout> </LinearLayout>

fragment.xml

<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"
tools:context="${relativePackage}.${activityClass}" > <Button
android:id="@+id/fragment_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginBottom="41dp"
android:text="kale" /> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/fragment_button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="46dp"
android:text="点击后传值"
android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>

MyFragment

package com.kale.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button; public class MyFragment extends Fragment{ private MyCallback mCallback;
//定义一个调用接口}
public interface MyCallback {
public void onBtnClick(View v);
}
String TAG = getClass().getName(); @Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.e(TAG, "F------------onAttach->");
if(!(activity instanceof MyCallback)) {
throw new IllegalStateException("fragment所在的Activity必须实现Callbacks接口");
}
//把绑定的activity当成callback对象
mCallback = (MyCallback)activity;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e(TAG, "F------------onActivityCreated->");
//一定要在定义好视图后才来初始化控件,不能放在onCreat()里面
Button btn = (Button)getActivity().findViewById(R.id.fragment_button);
btn.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
mCallback.onBtnClick(v);
}
});
} @Override
public void onDetach() {
super.onDetach();
Log.e(TAG, "F------------onDetach->");
mCallback = null;//移除前幅值为空
} }

fragment02.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"> <TextView
android:id="@+id/fragment_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="null"
android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/fragment_textView"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="传来的信息" /> </RelativeLayout>

MyFragment02

package com.kale.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; public class MyFragment02 extends Fragment{
public static final String KEY = "key"; String TAG = getClass().getName(); @Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.e(TAG, "F------------onCreateView->");
return inflater.inflate(R.layout.fragment02, container, false);
} @Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e(TAG, "F------------onActivityCreated->");
//一定要在定义好视图后才来初始化控件,不能放在onCreat()里面
TextView tv = (TextView)getActivity().findViewById(R.id.fragment_textView); tv.setText("haha");
Bundle bundle = getArguments();
if (bundle == null) {
tv.setText("默认值01");
}
else {
tv.setText(bundle.getString(KEY, "默认值02"));
}
} }

MainActivity

package com.kale.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button; import com.kale.activity.MyFragment.MyCallback; public class MainActivity extends ActionBarActivity implements MyCallback{ String TAG = getClass().getName(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG, "------------onCreate------------"); FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction(); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.add(R.id.container_fragment, new MyFragment())
.commit(); //不能用同个FragmentTransaction来加载两个fragment
fragmentManager.beginTransaction()
.add(R.id.container_fragment02, new MyFragment02())
.commit();
} @Override
protected void onStart() {
super.onStart();
Log.e(TAG, "------------onStart------------");
} @Override
protected void onRestart() {
super.onRestart();
Log.e(TAG, "------------onRestart------------");
} @Override
protected void onResume() {
super.onResume();
Log.e(TAG, "------------onResume------------");
} @Override
protected void onPause() {
super.onPause();
Log.e(TAG, "------------onPause------------");
} @Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.e(TAG, "------------onSaveInstanceState------------");
} @Override
protected void onStop() {
super.onStop();
Log.e(TAG, "------------onStop------------");
} @Override
protected void onDestroy() {
super.onDestroy();
Log.e(TAG, "------------onDestroy------------");
} @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.e(TAG, "------------onRestoreInstanceState------------");
} @Override
public void onBtnClick(View v) {
Button btn = (Button)v;
Log.i(TAG, btn.getText()+""); Bundle bundle = new Bundle();
bundle.putString(MyFragment02.KEY, btn.getText()+"");
MyFragment02 fragment = new MyFragment02();
fragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().
replace(R.id.container_fragment02, fragment)
.addToBackStack(null)
.commit(); }
}

源码下载:http://download.csdn.net/detail/shark0017/7709315

Fragment与Activity之间的通信的更多相关文章

  1. Android系列之Fragment(三)----Fragment和Activity之间的通信(含接口回调)

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  2. 适配器(adapter)与fragment之间、fragment与activity之间的通信问题

    一.适配器(adapter)与fragment之间通信 通过本地广播进行通信 步骤如下 在adapter中代码 声明本地广播管理 private LocalBroadcastManager local ...

  3. Fragment和activity之间的通信

    1>fragment可以调用getactivity()方法获取它所在的activity. 2>activity可以调用FragmentManager的findFragmentById()或 ...

  4. Fragment 与Activity之间的通信

    1.Fragment-->Activity 在fragment中的onAttach()中引用Activity实现的接口实例. 2Activity-->Fragment 直接调用 3多个Fr ...

  5. Fragment的生命周期和Activity之间的通信以及使用

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

  6. Android(Fragment和Activity之间通信)

    Fragment的使用可以让我们的应用更灵活的适配各种型号的安卓设备,但是对于Fragment和Activity之间的通信,很多朋友应该比较陌生,下面我们就通过一个实例来看一看如何实现. 一.Acti ...

  7. Fragmen和Activity之间的通信--接口和实现的分离(转)

    Fragmen和Activity之间的通信--接口和实现的分离(转) 分类: Android平台     在平板的开发过程中通常都会采用多个Fragment的实现方式,通常有一个为list的Fragm ...

  8. Activity之间的通信

    通常Activity之间的通信有三种方式:单向不传参数通信.单项传参数通信和双向通信. 这几种传递方式都需要通信使者Intent.以下将用代码来辅助理解. 1.单向不传递参数通信 public cla ...

  9. 安卓Fragment和Activity之间的数据通讯

    Fragment是Android3.0之后才推出来的.可以用来做底部菜单,现在很多APP都有用到这个底部菜单.当然TabHost也可以用来做底部菜单,但是Fragment来做,动画效果这些可以做得更炫 ...

随机推荐

  1. 上传文件被nginx全部缓存的问题

    nginx采用1.5.6. 后端采用nodejs+formidable的方式接受上传文件,本问题的对应与采用什么样的后端没太大关系,这里只是交代一下. 问题: 在前端页面上将文件上传,nginx没有将 ...

  2. Win8 app判断网络连接状态

    Win8 app判断网络连接状态 NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged; ...

  3. 导出Excel文件(针对Dev)

    文件类: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System. ...

  4. jquery内容选择器(匹配内容为空的元素)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. Linux System Calls Hooking Method Summary

    http://www.cnblogs.com/LittleHann/p/3854977.html http://www.cnblogs.com/cozy/articles/3175615.html h ...

  6. 让我们来讲讲,SCRUM和AGILE(资料来源:https://www.youtube.com/ 文中有代理参数配置)

    本期我们讨论的主题是项目管理 以前,一直以为“ Write the code, Change the world ”.但实质上,我们就一写代码的.如果我们能上升到项目管理的角度来实行Project M ...

  7. 容器--EnumMap

    一.概述 EnumMap是一类特殊的Map, 其特殊之处在于KEY需要是枚举类型,由于枚举类型的特点是值的个数是固定的,所以,对于EnumMap来说,其所能存储的个数也就是固定的了.这种类型的Map相 ...

  8. 设计3D标签

    java自带的Label太枯燥了,真是拿不出手啊. 所以,我们要设计3D标签!! 看看下面这张图 原理 看看这图,可以看到哈哈有三种颜色:白色.黑色和灰色 实现的时候并不像PS那样,按几个按钮就O了 ...

  9. Java基础学习 -- Java(OOP)程序的设计原则

    避免代码复制.解决方案:函数.父类: 封装.尽量private每个类的成员变量,用操作封装数据,减少类与类之间成员变量的直接调用,而是调用method,降低耦合: 可扩展性最大化.尽量使用框架+数据的 ...

  10. array's filter

    var arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, { }, { id: null }, { id: NaN ...