我有一个包含 TripMemberFragment 和 TripPhotosFragment 的 TripDetailFragment。在 TripMemberFragment 内部,我有一个私有实例变量 Trip trip。此变量在第一次调用 TripDetailFragment 时正确设置。但是,在 TripDetailFragment 的第二次打开时,此变量为空。
public class TripDetailFragment extends Fragment {
Trip trip;
Context context;
MainActivity.BottomNavAdapter adapter;
private final List<Fragment> fragments = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//inflate view
setUpFragments();
//return inflate view
}
private void setUpFragments(){
fragments.add(new TripMemberFragment(trip));
((TripMemberFragment)fragments.get(0)).setTrip(trip);
fragments.add(new TripPhotosFragment());
adapter = new MainActivity.BottomNavAdapter(getChildFragmentManager(), fragments);
vpTrip.setAdapter(adapter);
vpTrip.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
switch (i) {
case 0:
tripNavigation.setSelectedItemId(R.id.action_members);
break;
case 1:
tripNavigation.setSelectedItemId(R.id.action_photos);
break;
}
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
tripNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.action_members:
vpTrip.setCurrentItem(0);
return true;
case R.id.action_photos:
vpTrip.setCurrentItem(1);
return true;
default:
return false;
}
}
});
}
}
public class TripMemberFragment extends Fragment {
private Trip trip;
public TripMemberFragment(Trip trp) {
trip = trp;
}
public TripMemberFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
members = new ArrayList<>();
memberAdapter = new TripMemberAdapter(members, callbackMember);
rvMembers.setLayoutManager(new LinearLayoutManager(context));
rvMembers.setAdapter(memberAdapter);
loadMembers();
//return inflated view
}
public void loadMembers(){
try{
ParseRelation relation = trip.getRelation("user");
ParseQuery query = relation.getQuery();
query.findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> objects, ParseException e) {
Log.d("relation", objects.toString());
members.clear();
members.addAll(objects);
memberAdapter.notifyDataSetChanged();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
}
运行时没有记录错误或异常,但 TripDetailFragment 中的 trip 变量在第二次运行时调用 loadMembers() 时为空,但在调用片段的构造函数时似乎已正确设置。我认为将 setUpFragments() 放在 onCreateView() 中可能存在问题,但不知道它还能去哪里。