从其他片段返回时,片段内的Recyleview为空

时间:2019-05-25 14:07:48

标签: android android-fragments android-recyclerview fragment-backstack

我正在开发带有片段的应用程序(一个只有活动但有多个片段的应用程序)。

我遇到的问题是,当我转到一个片段并返回(系统后退按钮)到初始片段时,它的RecycleView现在为空。

奇怪的是,当我从另一个片段(也带有RecycleView)到相同片段时,不会发生此问题。

下面,我用RecycleView和MainActivity发布了这两个片段。

有人知道为什么会这样吗?

确实存在的片段有问题:

public class FavEventFragment extends Fragment implements RecyclerView.OnItemTouchListener {

    private static final String PAGE_NAME = "Saved Events";

    private TextView noEventsTextView;

    FavEventAdapter adapter;
    RecyclerView recyclerView;
    private EventViewModel eventViewModel;
    private List<Event> favEvents;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_favevent, container, false);

        MainActivity.changeLayoutWeight(true);
        MainActivity.setPageName(PAGE_NAME);

        favEvents = new ArrayList<>();

        recyclerView = rootView.findViewById(R.id.favEvent_list);
        noEventsTextView = rootView.findViewById(R.id.noFavEventsText);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        eventViewModel = ViewModelProviders.of(this).get(EventViewModel.class);
        eventViewModel.getFavEvents().observe(this, new Observer<List<Event>>() {

            @Override
            public void onChanged(@Nullable List<Event> games) {
                favEvents = games;
                updateUI();
            }
        });

        setRecycleViewGestures();

        return rootView;
    }

    private void updateUI() {
        if (adapter == null) {
            adapter = new FavEventAdapter(favEvents);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.swapList(favEvents);
        }
    }

    void setRecycleViewGestures() {

        recyclerView.addOnItemTouchListener(new RecycleGestures(getActivity(), recyclerView, new RecycleGestures.ClickListener() {
            @Override
            public void onClick(View view, int position) {

                EventDetailsFragment fragment = new EventDetailsFragment();

                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();

                transaction.setCustomAnimations(R.anim.enter_from_top, R.anim.exit_to_top, R.anim.enter_from_top, R.anim.exit_to_top);

                fragment.setObject(favEvents.get(position));
                transaction.addToBackStack(null);
                transaction.replace(R.id.fragment_container, fragment, "FRAGMENT").commit();
            }

            @Override
            public void onLongClick(View view, int position) { }
        }));

        ItemTouchHelper.SimpleCallback simpleItemTouchCallback =
                new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
                    @Override
                    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                        return false;
                    }

                    @Override
                    public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
                        int position = (viewHolder.getAdapterPosition());
                        eventViewModel.delete(favEvents.get(position));
                        favEvents.remove(position);
                        adapter.notifyItemRemoved(position);
                    }
                };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);
        recyclerView.addOnItemTouchListener(this);
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { return false; }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) { }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { }
}```


The fragment that **doesn't** have the problem:


public class EventsFragment extends Fragment {

    private static final String PAGE_NAME = "Upcoming Events";

    private RecyclerView eventList;
    private EventAdapter adapter;

    private AirsoftRepository airsoftRepository;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_shop, container, false);

        MainActivity.changeLayoutWeight(true);
        MainActivity.setPageName(PAGE_NAME);

        airsoftRepository = AirsoftRepository.getInstance();

        eventList = rootView.findViewById(R.id.item_list);

        eventList.setLayoutManager(new LinearLayoutManager(getActivity()));

        getEvents();

        return rootView;
    }

    private void getEvents() {
        airsoftRepository.getEvents(new OnGetEventsCallback() {
            @Override
            public void onSuccess(List<Event> events) {
                adapter = new EventAdapter(events, onClickCallback);
                eventList.setAdapter(adapter);
            }

            @Override
            public void onError() {
                Toast.makeText(getActivity(), "Please check your internet connection.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    OnEventsClickCallback onClickCallback = new OnEventsClickCallback() {
        @Override
        public void onClick(Event event) {

            EventDetailsFragment fragment = new EventDetailsFragment();

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();

            transaction.setCustomAnimations(R.anim.enter_from_top, R.anim.exit_to_top, R.anim.enter_from_top, R.anim.exit_to_top);

            fragment.setObject(event);
            transaction.addToBackStack(null);
            transaction.replace(R.id.fragment_container, fragment, "FRAGMENT").commit();
        }
    };
}

2 个答案:

答案 0 :(得分:0)

 //Instead of replace use add() method

 transaction.add(R.id.fragment_container, fragment, "FRAGMENT").commit();

答案 1 :(得分:0)

替换片段会导致其视图层次结构被破坏。当前,您在重新输入片段时正在泄漏适配器。

向片段添加替代以清理当前适配器并查看引用:

@Override
public void onDestroyView(){
    recyclerView.setAdapter(null);
    adapter = null;
    recyclerView = null;
}

理想情况下,您的适配器应在onCreate期间创建,并且无论视图状态如何都可以正常运行。