我个人将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. 页面置换算法 - FIFO、LFU、LRU

    缓存算法(页面置换算法)-FIFO. LFU. LRU 在前一篇文章中通过leetcode的一道题目了解了LRU算法的具体设计思路,下面继续来探讨一下另外两种常见的Cache算法:FIFO. LFU ...

  2. 观察者模式(Observer pattern)

    知识点 使对象之间达到松耦合的效果. 观察者模式定义了对象之间一对多的关系.主题用一个共同的接口来更新观察者. 观察者和被观察者之间通过松耦合的方式结合,被观察者不用理会观察者的实现细节,只需要观察者 ...

  3. 实现多表关联来方便你的SELECT查询功能

    这次来学习一下多表关联.比如在数据中创建下面几张表,你可以从主键PRIMARY KEY与外键FOREIGN KEY来看到这几张表它们之间的关系. 场所表[dbo].[SixS_Location]: 主 ...

  4. C#写快速排序

    //先上快排代码------------------------------------------------------------------------public static void Q ...

  5. 关于JQuery(最后一点动画效果*)

    1,$(':radio').val(['1','2','3']);//特殊写法,把值为1 2 3的都选中. 2,math.abs(len)取绝对值 3,按钮高亮显示,一般是配置两个按钮,一个普通的,一 ...

  6. 从NavigationController 下的UITableView中移除 header

    this.AutomaticallyAdjustsScrollViewInsets = false; 解析:AutomaticallyAdjustsScrollViewInsets为系统自动为适应na ...

  7. JS的预编译和执行顺序 详析(及全局与局部变量)

    最近在复习javascript的事件处理时发现了一个问题,于是总结一下:javascript的预编译和执行顺序的问题:   <html> <head> <title> ...

  8. 容器--EnumMap

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

  9. 《Head First Java》——认识变量

    对象的引用 Book b = new Book(); Book c = new Book(); Book d = c;                   // 声明新的Book引用变量,但不创建新的 ...

  10. jQuery选择器。 5.21 《深夜还在编码的你》

    (之所以字体弄那么大是因为省眼,程序员不容易,程序员的眼睛更不容易,请保护我们的眼睛) 选择器是jQuery的根基,在jQuery中,对事件处理.遍历DOM和Ajax操作都依赖于选择器. 熟练地使用选 ...