我有两个片段片段A和片段B.我在主要活动中使用添加片段方法
String backStateName = fragment.getClass().getName();
FragmentManager fragmentManager = getSupportFragmentManager();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.add(R.id.frame_container_admin, fragment, backStateName);
ft.addToBackStack(backStateName);
ft.commit();
}
在此之后,每当我从片段B回来时,我想从服务器重新加载数据。我怎么处理这个?
答案 0 :(得分:1)
在您的活动中
为backstackchange创建一个监听器
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
try {
//Get current visible fragment
FragmentManager fragmentManager = ((AppCompatActivity) activity).getSupportFragmentManager();
Fragment currentVisibleFragment = fragmentManager.findFragmentById(R.id.container_fragment);
if(currentVisibleFragment instanceof FragmentB){
//Cast currentVisibleFragment to Fragment B and call method to request data again.
((FragmentB)currentVisibleFragment).requestData();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用您的请求代码在片段B中创建请求数据方法。