您需要将您的数据从Fragment X传递到您的FragmentActivity,这会将此数据传递到您的Fragment Y.您通过在您的fragment类中定义的接口来实现此目的,并实例化一个在onAttach()。如何做到这一点这里 Communication With other Fragments
简单的例子
更多信息,可以考虑片段A和片段B片段A是列表片段,每当一个项目被选中它会有什么变化显示在片段B.很简单,对吗?
首先,定义片段A.
public class FragmentA extends ListFragment{
//onCreateView blah blah blah
}
而这里的片段B
public class FragmentB extends Fragment{
//onCreateView blah blah blah
}
这是我的FragmentActivity将统治他们都
public class MainActivity extends FragmentActivity{
//onCreate
//set up your fragments
}
想必你有这样的事情已经,现在这里是你将如何改变FragmentA(我们需要从中获取一些数据的列表片段)。
public class FragmentA extends ListFragment implements onListItemSelectedListener, onItemClickListener{
OnListItemSelectedListener mListener;
//onCreateView blah blah blah
// Container Activity must implement this interface
public interface OnListItemSelectedListener {
public void onListItemSelected(int position);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mListener = (OnListItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnListItemSelectedListener");
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//Here's where you would get the position of the item selected in the list, and pass that position(and whatever other data you need to) up to the activity
//by way of the interface you defined in onAttach
mListener.onListItemSelected(position);
}
这里最重要的考虑是你的父Activity实现了这个接口,否则你会得到一个异常。如果成功实施,每次选择列表片段中的项目时,您的活动都会被通知其位置。很明显,你可以用任何数量或类型的参数来改变你的接口,在这个例子中,我们只是传入整数位置。希望这个澄清一个人,祝你好运。
有很多方法可以做到这一点,我喜欢尽可能的去耦合,为此我喜欢一个事件总线。请参阅otto,例如:http://square.github.io/otto/。 (让你摆脱所有的界面/监听器,传递数据,用强大的类型来做,用简洁明了的方式来做。) –
它看起来很有希望。我必须检查一下。谢谢你的提示。 –