问题描述
我已经超过2引用和尽我所能理解2片段之间的通信。随着从previous问题的帮助就在这里+ 2引用我能想出这个code。什么我必须把我的FragB检索选择在ListFragment弗拉加取得了用户?
主要活动:
公共类MainActivity扩展活动实现OnDataPass {
...
@覆盖
公共无效onDataPass(字符串数据){
// TODO自动生成方法存根
弗拉加为Transaction1 =((弗拉加)getFragmentManager()findFragmentByTag(ItemRoleList));
transaction1.dataPasser.onDataPass(数据);
}
}
下面是弗拉加:
公共类弗拉加扩展ListFragment {
OnDataPass dataPasser;
公共接口OnDataPass {
公共无效onDataPass(字符串数据);
}
@覆盖
公共无效onAttach(活性){
super.onAttach(一);
//这将确保集装箱活动已实施
//回调接口。如果不是,它抛出一个异常
尝试 {
dataPasser =(OnDataPass)一个;
}赶上(ClassCastException异常E){
抛出新ClassCastException异常(a.toString()
+必须实现OnHeadlineSelectedListener);
}
}
下面是我的理解。你有拖片段(A,B)的活性。 A是列表片段。关于选择在一个项目,你必须通过一个字符串到B。
第一个覆盖 onListItemClick()
在片段A
FragemtA:
公共类碎裂扩展ListFragment {
...
无效onListItemClick(ListView的L,视图V,INT位置,长的id){
datapasser.onDatapass(数据)//这里传递字符串
}
}
在您的活动的onDataPass方式:
无效onDataPass(字符串数据){
FragmentB dataUser = getFragmentB(); //你FragmentB对象
dataUser.use(数据);
}
片段B:
公共类FragmentB扩展片段{
...
无效的使用(字符串数据){
//这里使用的数据
}
}
I have been over 2 references and tried my best to understand the communication between 2 fragments. With the help from a previous question on here + the 2 references I was able to come up with this code. What would I have to put in my FragB to retrieve the choice the user made in ListFragment FragA?
Main Activity:
public class MainActivity extends Activity implements OnDataPass{
...
@Override
public void onDataPass(String data) {
// TODO Auto-generated method stub
FragA transaction1 = ((FragA) getFragmentManager().findFragmentByTag("ItemRoleList"));
transaction1.dataPasser.onDataPass(data);
}
}
Here is FragA:
public class FragA extends ListFragment{
OnDataPass dataPasser;
public interface OnDataPass{
public void onDataPass(String data);
}
@Override
public void onAttach(Activity a) {
super.onAttach(a);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
dataPasser = (OnDataPass) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
Here is what i understood. You have tow fragments(A, B) in an activity. A is a list fragment. on selecting an item in A, you have to pass a String to B.
First override onListItemClick()
in your Fragment A
FragemtA:
public class FragmentA extends ListFragment{
...
void onListItemClick(ListView l, View v, int position, long id){
datapasser.onDatapass(data)//here pass the String
}
}
In your activity's onDataPass method:
void onDataPass(String data){
FragmentB dataUser = getFragmentB();//Your FragmentB object
dataUser.use(data);
}
Fragment B:
public class FragmentB extends Fragment{
...
void use(String data){
//here use the data
}
}
这篇关于片段接口与另一个片段进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!