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来做,动画效果这些可以做得更炫 ...
随机推荐
- log4net的配置详解
log4net是一款优秀的第三方日志框架,可以很容易的加载到开发项目中(引用log4net的dll,再配置些基本参数即可),帮助程序员把日志信息输出到各种不同的目标,常见的有文本.数据库.window ...
- jquery 进阶
1.0 jquery的ajax同步和异步区别 2.0 cdnjquery加载失败加载本地 <script type="text/javascript" src="/ ...
- 实现了IEnumerable接口的GetEnumerator 即可使用 Foreach遍历,返回一个IEnumerator对象
#region 程序集 mscorlib.dll, v4.0.0.0 // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framewor ...
- 【SQL】小心字符串拼接导致长度爆表
请看代码: DECLARE @max VARCHAR(max) SET @max='aaa...' --这里有8000个a +'bb' --连接一个varchar常量或变量 SELECT LEN(@m ...
- Jquery获取checkbox属性checked为undefined
说明:本文来自新浪博客,因为无法收藏,故直接copy过来备注,以后好查询 原网址:http://blog.sina.com.cn/s/blog_6810dfc20101jddq.html 使用jQue ...
- MongoDB在实际项目中的使用
MongoDB简介 MongoDB是近些年来流行起来的NoSql的代表,和传统数据库最大的区别是支持文档型数据库. 当然,现在的一些数据库通过自定义复合类型,可变长数组等手段也可以模拟文档型数据库. ...
- Win10 IoT C#开发 3 - GPIO Pin 控制发光二极管
Windows 10 IoT Core 是微软针对物联网市场的一个重要产品,与以往的Windows版本不同,是为物联网设备专门设计的,硬件也不仅仅限于x86架构,同时可以在ARM架构上运行. 上一篇文 ...
- 关于【error C3646: 未知重写说明符】的若干种可能性
如果在程序中出现了error C3646,那么这个错误可能是由多种问题所导致的,这篇文章将对多种错误及对应解决方法进行分析. 在MSDN的官方网站中,Complier Error C3646的定义为u ...
- Python 3 利用 subprocess 实现管道( pipe )交互操作读/写通信
这里我们用Windows下的shell来举例: from subprocess import * #因为是举例,就全部导入了 为了方便你理解,我们用一个很简单的一段代码来说明: 可以看见我们利用Pop ...
- Codeforces Round #369 (Div. 2)---C - Coloring Trees (很妙的DP题)
题目链接 http://codeforces.com/contest/711/problem/C Description ZS the Coder and Chris the Baboon has a ...