Fragments之间的交互(实现参数传递)

日常开发中,通常Fragments之间可能需要交互,比如基于用户事件改变Fragment的内容。所有Fragment之间的交互需要通过他们关联的Activity,两个Fragment之间不应该直接交互。

采用接口回调的方式来实现Fragments之间的交互,大致分为四步:

1.定义一个接口

  • 为了让Fragment与Activity交互,可以在Fragment类中定义一个接口,并在Activity中实现。Fragment在它们的生命周期的onAttach()方法中获取接口的实现,然后调用接口的方法来与Activity交互。

定义接口的代码如下:

public class ListFragment extends Fragment implements AdapterView.OnItemClickListener {

    private ListView mListView;
private ListAdapter mAdapter;
private List<String> mData; public ListFragment() {
// Required empty public constructor
} public static ListFragment newInstance(String type) {
Bundle args = new Bundle();
args.putString("type", type);
ListFragment fragment = new ListFragment();
fragment.setArguments(args);
return fragment;
} @Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mData == null) {
mData = new ArrayList<>();
}
loadData();
} private void loadData() {
for (int i = 0; i < 10; i++) {
mData.add("Item" + i);
}
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
mListView = (ListView) rootView.findViewById(R.id.list_view); mAdapter = new ListAdapter(getActivity(), mData);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
return rootView;
} @Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mOnListItemSelectedListener = (OnListItemSelectedListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnListItemSelectedListener");
}
} @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mOnListItemSelectedListener.onListItemSelected(position);
} private OnListItemSelectedListener mOnListItemSelectedListener; public interface OnListItemSelectedListener {
void onListItemSelected(int position);
} /* ================适配器相关===============*/
public class ListAdapter extends BaseAdapter { private List<String> mData;
private Context mContext; public ListAdapter(Context context, List<String> data) {
this.mContext = context;
this.mData = data;
} @Override
public int getCount() {
return mData.size() == 0 ? 0 : mData.size();
} @Override
public Object getItem(int position) {
return mData == null ? null : mData.get(position);
} @Override
public long getItemId(int position) {
return position;
} @Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
holder.mTextView = (TextView) convertView.findViewById(R.id.text_view);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String text = mData.get(position);
if (text != null && !"".equals(text)) {
holder.mTextView.setText(text);
}
return convertView;
} public class ViewHolder {
TextView mTextView;
}
} }
  • 现在Fragment就可以通过OnListItemSelectedListener 接口实例的mOnListItemSelectedListener中的onListItemSelected()方法与Activity传递消息。
  • 我这个例子实现的是在ListFragment中点击ListView的一个Item,把这个Item的position传递给DetailFragment,DetailFragment展示具体的信息,如新闻列表,点击Item之后进入新闻详情页。
  • 当我们点击Item时,ListFragment用回调接口来传递事件给父Activity。
 @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mOnListItemSelectedListener.onListItemSelected(position);
}

2.实现接口

  • 为了接收回调事件,宿主Activity必须实现Fragment中定义的接口。
  • MainActivity实现了ListFragment中的接口,如下代码:
public class MainActivity extends AppCompatActivity
implements ListFragment.OnListItemSelectedListener { private static final String TAG = "MainActivity"; private ListFragment mListFragment; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mListFragment = ListFragment.newInstance("ListFragment");
ActivityUtil.addFragmentToActivity(getSupportFragmentManager(),
mListFragment, R.id.frame_container);
} @Override
public void onListItemSelected(int position) {
Log.d(TAG, position + "");
Bundle args = new Bundle();
args.putInt("position",position);
DetailFragment fragment = DetailFragment.newInstance("DetailFragment");
fragment.setArguments(args);
ActivityUtil.addFragmentToActivity(getSupportFragmentManager(), fragment, R.id.frame_container);
}
}

3.传递消息给Fragment

  • 宿主MainActivity中还包含了另外一个Fragment(DetailFragment),DetailFragment用来展示回调方法中指定Item的内容。在这种情况下,MainActivity可以把回调方法中接收到的position传递给DetailFragment。
 @Override
public void onListItemSelected(int position) {
Log.d(TAG, position + "");
Bundle args = new Bundle();
args.putInt("position",position);
DetailFragment fragment = DetailFragment.newInstance("DetailFragment");
fragment.setArguments(args);
ActivityUtil.addFragmentToActivity(getSupportFragmentManager(), fragment, R.id.frame_container);
}

4.接收传递的参数

  • 在DetailFragment中接收ListFragment传递的position参数
public class DetailFragment extends Fragment {

    private TextView mTextView;
private Bundle args; public DetailFragment() {
// Required empty public constructor
} public static DetailFragment newInstance(String type) {
Bundle args = new Bundle();
args.putString("type", type);
DetailFragment fragment = new DetailFragment();
fragment.setArguments(args);
return fragment;
} @Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();//获取传递的参数
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
mTextView = (TextView) rootView.findViewById(R.id.text_view);
mTextView.setText(args.get("position").toString());
return rootView;
}
}

这样就实现了两个Fragment之间的交互。其核心就是拥有同一个宿主Activity的Fragments利用接口回调的方式实现参数的传递。

博客地址:http://tonycheng93.github.io/

源码地址:https://github.com/tonycheng93/Fragment2Fragment

Fragments之间的交互(实现参数传递)的更多相关文章

  1. Salesforce视图与控制器之间的交互

    刚接触Salesforce,过程的确是比较艰难了,中文资料几乎没有,看英文资料学的效率却不高,不过看了一段时间的英文资料发现自己英语水平挺高不少啊,现在看都不用工具翻译,早知道就再次尝试报个6级,看下 ...

  2. python基础--面向对象基础(类与对象、对象之间的交互和组合、面向对象的命名空间、面向对象的三大特性等)

    python基础--面向对象 (1)面向过程VS面向对象 面向过程的程序设计的核心是过程(流水线式思维),过程即解决问题的步骤,面向过程的设计就好比精心设计好一条流水线,考虑周全什么时候处理什么东西. ...

  3. 我的Android第五章:通过Intent实现活动与活动之间的交互

    Intent在活动的操作 作用: Itent是Android程序中各个组件直接交换的一个重要方式可以指定当前组件要执行任务同时也可以给各个组件直接进行数据交互              同时Inten ...

  4. AngularJs-指令和指令之间的交互(动感超人)

    前言: 上节我们学习到了指令和控制器之间的交互,通过给指令添加动作,调用了控制器中的方法.本节我们学习指令和指令之间是如何交互的,我们通过一个小游戏来和大家一起学习,听大漠老师说这是国外的人写的dem ...

  5. OC和JS之间的交互

    OC和JS之间的交互 目录 对OC和JS之间交互的理解 JS调用OC OC调用JS 对OC和JS之间交互的理解 JS调用OC JS文件 function sendCommand(cmd,param){ ...

  6. 安卓任意两个或多个Fragment之间的交互与刷新界面

    平时项目中遇到一个问题:在子fragment中刷新父fragment的界面,通俗的说也就是在任何一个fragment中来刷新另一个fragment.大家都知道activity和fragment之间的交 ...

  7. WPF自学入门(八)WPF窗体之间的交互

    今天我们一起来看一下WPF窗体之间的交互-窗体之间的传值.有两个窗体,一个是父窗体,一个是子窗体.要将父窗体的文本框中的值传递给子窗体中的控件.我们该怎么实现? 接下来我们一起来实现窗体之间的传值,在 ...

  8. python 全栈开发,Day18(对象之间的交互,类命名空间与对象,实例的命名空间,类的组合用法)

    一.对象之间的交互 现在我们已经有一个人类了,通过给人类一些具体的属性我们就可以拿到一个实实在在的人.现在我们要再创建一个狗类,狗就不能打人了,只能咬人,所以我们给狗一个bite方法.有了狗类,我们还 ...

  9. iOS原生和React-Native之间的交互1

    今天,记录一下iOS原生和React-Native之间的交互.如果第一次接触最好先移步至 http://www.cnblogs.com/shaoting/p/6388502.html 先看一下怎么在i ...

随机推荐

  1. 【JAVA】"骗人"的“replaceAll”

    Java String类中有个方法叫:replaceAll,从表面上看,他的意思是把所有的regex替换成replacement. public String replaceAll(String re ...

  2. 解决错误: java.lang.NoClassDefFoundError: antlr/RecognitionException

    网络质量不好的情况下,访问maven.org网站下载jar包,很有可能下载的包不完整或损坏的(表面看不出来):所以,最好的办法就是-直接到maven网站下载,然后放到对应的.m2目录,然后eclips ...

  3. 详解SPI中的极性CPOL和相位CPHA

    SPI由于接口相对简单(只需要4根线),用途算是比较广泛,主要应用在 EEPROM,FLASH,实时时钟,AD转换器,还有数字信号处理器和数字信号解码器之间.即一个SPI的Master通过SPI与一个 ...

  4. IOS雕虫小技

    1,你所不知道的Mac截图的强大 2,抓包工具WireShark开发必备,需要装X11插件 3,Mac远程控制Windows桌面-CoRD.或者TeamViewer 4,Mac下解压缩BetterZi ...

  5. 二叉查找树(一)之 图文解析 和 C语言的实现

    概要 本章先对二叉树的相关理论知识进行介绍,然后给出C语言的详细实现.关于二叉树的学习,需要说明的是:它并不难,不仅不难,而且它非常简单.初次接触树的时候,我也觉得它似乎很难:而之所产生这种感觉主要是 ...

  6. extractCSS – 帮助你从 HTML 中快速分离出 CSS

    extractCSS 是一个免费的基于 Web 的应用程序,能够从 HTML 中提取风格相关的信息,包括 id.class 和内联样式,而且输出可以定制(缩进和括号的用法).该工具非常有用,当我们快速 ...

  7. The Top 10 Javascript MVC Frameworks Reviewed

    Over the last several months I have been in a constant search for the perfect javascript MVC framewo ...

  8. 第十一篇 SQL Server代理维护计划

    本篇文章是SQL Server代理系列的第十一篇,详细内容请参考原文 在这一系列的上一篇,我们看了使用代理帐户模仿Windows安全上下文完成作业步骤的工作.大多数子系统支持代理账户,同时子系统限制代 ...

  9. Qt之QAbstractItemView视图项拖拽(一)

    一.需求说明 最近在搞视图项的拖拽,也上网查了一些资料,好多的文档都是一样的,只是被不通的网站所收录了(也有可能是被爬过去的,不明所以),不过也有一些文档写的不错,不过就是太简易,都是点睛之笔,总之功 ...

  10. 一篇通俗易懂的讲解OpenGL ES的文章

    电脑或者手机上做图像处理有很多方式,但是目前为止最高效的方法是有效地使用图形处理单元,或者叫 GPU.你的手机包含两个不同的处理单元,CPU 和 GPU.CPU 是个多面手,并且不得不处理所有的事情, ...