Fragment与Activity之间的通信
我个人将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之间的通信的更多相关文章
- Android系列之Fragment(三)----Fragment和Activity之间的通信(含接口回调)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...
- 适配器(adapter)与fragment之间、fragment与activity之间的通信问题
一.适配器(adapter)与fragment之间通信 通过本地广播进行通信 步骤如下 在adapter中代码 声明本地广播管理 private LocalBroadcastManager local ...
- Fragment和activity之间的通信
1>fragment可以调用getactivity()方法获取它所在的activity. 2>activity可以调用FragmentManager的findFragmentById()或 ...
- Fragment 与Activity之间的通信
1.Fragment-->Activity 在fragment中的onAttach()中引用Activity实现的接口实例. 2Activity-->Fragment 直接调用 3多个Fr ...
- Fragment的生命周期和Activity之间的通信以及使用
Fragment通俗来讲就是碎片,不能单独存在,意思就是说必须依附于Activity,一般来说有两种方式把Fragment加到Activity,分为静态,动态. 静态即为右键单击,建立一个Fragme ...
- Android(Fragment和Activity之间通信)
Fragment的使用可以让我们的应用更灵活的适配各种型号的安卓设备,但是对于Fragment和Activity之间的通信,很多朋友应该比较陌生,下面我们就通过一个实例来看一看如何实现. 一.Acti ...
- Fragmen和Activity之间的通信--接口和实现的分离(转)
Fragmen和Activity之间的通信--接口和实现的分离(转) 分类: Android平台 在平板的开发过程中通常都会采用多个Fragment的实现方式,通常有一个为list的Fragm ...
- Activity之间的通信
通常Activity之间的通信有三种方式:单向不传参数通信.单项传参数通信和双向通信. 这几种传递方式都需要通信使者Intent.以下将用代码来辅助理解. 1.单向不传递参数通信 public cla ...
- 安卓Fragment和Activity之间的数据通讯
Fragment是Android3.0之后才推出来的.可以用来做底部菜单,现在很多APP都有用到这个底部菜单.当然TabHost也可以用来做底部菜单,但是Fragment来做,动画效果这些可以做得更炫 ...
随机推荐
- 一个比较有意思的C语言问题
先看代码吧,学习c语言结构体中看到的一个问题 #include<stdio.h> int main(){ struct{ int a:2; }x; x.a=; x.a=x.a+; prin ...
- a:link a:visited a:hover a:active四种伪类选择器的区别
a:link选择网页中所有没有被visited的a标签,就是没有鼠标悬停hover或者点击click(a链接没有被访问时的样式) a:visited选择网页中所有已经被click的a链接,用来告诉用户 ...
- Android 获取可靠的手机编码
项目中出现了将设备和用户信息进行绑定的需求.最先想到的是IMEI串码和IMSI串码.手机登陆的时候一直都没有问题.换了一个平板中之后IMEI和IMSI串码都获取不到了.后来查了一下原因,是因为平板上是 ...
- 【转】 Newtonsoft.Json高级用法
手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数 ...
- redis-desktop-manager
介绍一款Redis图形管理工具:redis-desktop-manager 下载地址:点击打开链接 我们打开redis-cl.exe 客户端,在里面添加了key= name ,value=heyang ...
- SQL vs NoSQL 没有硝烟的战争!
声明:本文译自SQL vs NoSQL The Differences,如需转载请注明出处. SQL(结构化查询语言)数据库作为一个主要的数据存储机制已经超过40个年头了.随着web应用和像MySQL ...
- TestNG官方文档中文版(5)-测试方法/类和组
5 - Test methods, Test classes and Test groups 5.1 - Test groups TestNG容许执行复杂的测试方法分组.不仅可以申明方法属于组,而且可 ...
- 系统配置文件的加载设置-以xml文件为例
前言:开发中经常会遇到加载一些配置文件信息,这些信息变化的概率很小,不需要实时的更新.这样的信息放在数据库里自然是不合适的,所以最好的办法是写在配置文件中,在程序第一次运行的时候加载到内存,以后用到的 ...
- GJM: Unity3D AssetBundle 手记 [转载]
这篇文章从AssetBundle的打包,使用,管理以及内存占用各个方面进行了比较全面的分析,对AssetBundle使用过程中的一些坑进行填补指引以及喷! AssetBundle是Unity推荐的 ...
- 如何解决CRUD操作中与业务无关的字段赋值
提高效率一直是个永恒的话题,编程中有一项也是可以提到效率的,那就是专注做一件事情,让其它没有强紧密联系的与之分开.这里分享下我们做CRUD时遇到的常见数据处理场景: 数据库表字段全部设计为非空,即使这 ...