片段中的片段在第二次调用时未设置类变量

时间:2018-07-20 20:53:24

标签: android android-fragments null fragment fragment-oncreateview

我有一个TripDetailFragment,其中包含TripMemberFragment和TripPhotosFragment。在TripMemberFragment内部,我有一个私有实例变量Trip trip。第一次调用TripDetailFragment时正确设置了此变量。但是,在TripDetailFragment的第二个开口处,此变量为null。

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();
      }

   }
}

运行时没有记录的错误或异常,但是在第二次运行中调用loadMembers()时,TripDetailFragment中的trip变量为null,但是在调用该片段的构造函数时似乎正确地设置了该变量。我认为将setUpFragments()放在onCreateView()中可能会有问题,但不知道它还能去哪里。

1 个答案:

答案 0 :(得分:0)

首先,您应该使用静态工厂方法来创建Fragment这样的新实例:

public static TripMemberFragment newInstance(Trip trip) {
    TripMemberFragment fragment = new TripMemberFragment();
    Bundle extras = new Bundle();
    extras.putParcelable(“EXTRA_TRIP, trip);  // or use here putSerializable method if you working with Serializable objects
    fragment.setArguments(extras);
    return fragment;
}

现在您应该在每次需要Fragment实例时使用此 newInstance 方法。因此,您需要从片段中删除所有构造函数,以防止使用构造函数创建片段的实例。

旅行对象可以从Fragment参数获得,如下所示:

getArguments().getParcelable(“EXTRA_TRIP”) // or use here getSerializable method if you working with Serializable objects

TripDetailFragment 内的 setUpFragments 方法中,您可以替换以下行:

fragments.add(new TripMemberFragment(trip));
((TripMemberFragment)fragments.get(0)).setTrip(trip);
fragments.add(new TripPhotosFragment());

具有:

fragments.add(TripMemberFragment.newInstance(trip));
fragments.add(pTripPhotosFragment.newInstance());

我有种感觉,传递的对象会以某种方式丢失。如果您传递带有Arguments的对象,则该对象应保留在 getArguments()方法内的片段实例上。