Fragment与Activity通信

将Fragment添加到Activity中有如下两种方式:

1.在布局文件中使用<fragment../>元素添加Fragment,<fragment.../>元素的android:name属性指定

Fragment的实现类。

2.在Java代码中通过FragmentTransaction对象的add()方法来添加Fragment。

将Fragment添加到Activity之后,Fragment必须与Activitiy交互信息:

1.Fragment获取它所在的Activity:调用Fragment的getActivity()方法即可返回它所在的Activity。

2.Activity获取它包含的Fragment:调用Activity关联的FragmentManager的findFragmentById(int id)

或findFragmentByTag(String tag)方法即可获取指定的Fragment。

Fragment与Activity可能还需要相互传递数据

1.Activity向Fragment传递数据:在Activity中创建Bundle数据包,并调用Fragment的

SetArguments(Bundle bundle)方法即可将Bundle数据包传递给Fragment。

2.Fragment向Activity传递数据或Activity需要在Fragment运行中进行实时通信:在Fragment中定义一个内

部回调接口,再让包含该Fragment的Activity实现该回调接口,这样Fragment即可调用该回调接口将数据

传递给Activity。

例子:

布局文件

<?xmlversion="1.0"encoding="utf-8"?><!--定义一个水平排列的LinearLayout,并指定使用中等分隔条--><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginLeft="16dp"android:layout_marginRight="16dp"android:divider="?android:attr/dividerHorizontal"android:showDividers="middle"><!--添加一个Fragment--><fragmentandroid:name="org.crazyit.app.BookListFragment"android:id="@+id/book_list"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"/><!--添加一个FrameLayout容器--><FrameLayoutandroid:id="@+id/book_detail_container"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="3"/></LinearLayout>

SelectBookActivity文件

importandroid.app.Activity;importandroid.os.Bundle;publicclassSelectBookActivityextendsActivityimplementsBookListFragment.Callbacks{@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);//加载/res/layout目录下的activity_book_twopane.xml布局文件setContentView(R.layout.activity_book_twopane);}//实现Callbacks接口必须实现的方法@OverridepublicvoidonItemSelected(Integerid){//创建Bundle,准备向Fragment传入参数Bundlearguments=newBundle();arguments.putInt(BookDetailFragment.ITEM_ID,id);//创建BookDetailFragment对象BookDetailFragmentfragment=newBookDetailFragment();//向Fragment传入参数fragment.setArguments(arguments);//使用fragment替换book_detail_container容器当前显示的FragmentgetFragmentManager().beginTransaction().replace(R.id.book_detail_container,fragment).commit();//①}}





更多相关文章

  1. Android(安卓)Activity界面切换添加动画特效
  2. Android(安卓)Wifi模块分析(三)
  3. Android中dispatchDraw分析
  4. "Failed to fetch URL https://dl-ssl.google.com/android/repos
  5. Android四大基本组件介绍与生命周期
  6. Android(安卓)流式布局FlowLayout(搜索历史),多布局、删除、添加
  7. Android(安卓)Service AIDL
  8. Android调用天气预报的WebService简单例子
  9. android打电话发短信

随机推荐

  1. [记录]Navigation无title注意事项
  2. Android中的事件传递
  3. Android中关于退出和Toast的引用
  4. windows下使用git下载android 代码
  5. Android中SeekBar和RatingBar用法实例分
  6. ionic android 发布
  7. 今天聊点有的没的~
  8. android中如何自定义attributes
  9. Android开发之多点触摸(Multitouch)[转]
  10. 定义各种事物的类型