Fragment 和 Activity 之间通信

Posted 鹰头猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Fragment 和 Activity 之间通信相关的知识,希望对你有一定的参考价值。

在 Activity 中获取 Fragment 实例:

  FragmentManager 提供了一个类似于 findViewById 的方法,专门用于从布局文件中获取 Fragment 实例:

//通过挂载点的容器id获取对应的 Fragment 实例
RightFragment rightFragment = (RightFragment) getSupportFragmentManager().findFragmentById(R.id.right_fragment);

 

在 Fragment 中获取 Activity 实例:

  Fragment 中提供了一个 getActivity 方法,用于获取托管该 Fragment 的 Activity 实例:

MainActivity activity = (MainActivity) getActivity();

 

以上是关于Fragment 和 Activity 之间通信的主要内容,如果未能解决你的问题,请参考以下文章