1. 碎片与碎片之间直接通信:
FragmentOther other = (FragmentOther) getFragmentManager(). findFragmentByTag("other");
calledFragment.setTargetFragment(this, 0);
getFragmentManager().beginTransaction().add(calledFragment, "work").commit();
TextView tv = (TextView)getTargetFragment().getView().findViewById(R.id.text1);
tv.setText("Set from the called fragment");
FragmentOther other = (FragmentOther) getFragmentManager(). findFragmentByTag("other");
other.callMethod(...);
2. 当一个碎片希望启动另一个碎片时, Fragment类 setTargetFragment(Fragment f, int requestCode)方法 支持调用碎片使用被调用碎片来设置它的身份.看一段示例代码:
Fragment calledFragment = new CalledFragment();calledFragment.setTargetFragment(this, 0);
getFragmentManager().beginTransaction().add(calledFragment, "work").commit();
这里创建一个新calledFragment 对象,在被调用碎片calledFragment 上将调用碎片设置为当前碎片 this, 使用事务将calledFragment 添加到碎片管理器和Activity 中, 当被 调用碎片calledFragment运行时, 它可以调用 getTargetFragment(), 将返回调用碎片的引用. 使用此引用, 被调用碎片可以调用 this(即调用碎片) 上的方法.
TextView tv = (TextView)getTargetFragment().getView().findViewById(R.id.text1);
tv.setText("Set from the called fragment");