在做项目时遇到一个问题,我在A fragment中展示从服务器拿到的数据,在B fragment,添加数据到服务器,同时B fragment同步刷新,纠结了很久都不行,因为我创建fragment时用的是:show与hide
switch (index) {
case 0:
if (fragSendControu == null) {
fragSendControu = new Frag_Send_Controu();
ft.add(R.id.send_frag, fragSendControu);
}
ft.show(fragSendControu);
// ft.replace(R.id.send_frag, new Frag_Send_Controu());
break;
case 1:
if (fragSendAdd == null) {
fragSendAdd = new Frag_Send_Add();
ft.add(R.id.send_frag, fragSendAdd);
}
ft.show(fragSendAdd);
// ft.replace(R.id.send_frag, new Frag_Send_Add());
break;
}
ft.commit();
然而show,hide切换时只是把原来的界面隐藏了并没有需要从新调用;狮子啊没办法了就使用了replace(它在每次调用时都是从新创建一个新的,你在多个fragment之间稍微点快速些她就崩了);
今天在做着时突然想到去看看fragment的生命周期在使用show,hide时他的生命周期是怎么样的。
突然发现我可以在隐藏Bfragment的时候调用Afragment的onResume,或onStart(),于是我就:
switch (index) {
case 0://开启A fragment
if(B!=null){//如果B不为空,隐藏B fragment
ft.hide(B);
A.onResume();//调用A fragment的onResume
}
if (A== null) {
A= new A();
ft.add(R.id.send_frag, A);
}
ft.show(A);
// ft.replace(R.id.send_frag, new A());
break;
case 1://开启B fragment
if(A!=null){
ft.hide(A);//如果A不为空,隐藏A fragment
}
if (B== null) {
B= new B();
ft.add(R.id.send_frag, B);
}
ft.show(B);
// ft.replace(R.id.send_frag, new B());
break;
}
ft.commit();
A fragment:
@Override
public void onResume() {
super.onResume();
//这儿放你想要运行的函数
Logutil.d(tag, "onResume");
}
这样就实现了你在B fragment向服务器添加完数据后,点击A fragment时,Afragment同步刷新;