被破坏的片段内容仍保留在屏幕上

时间:2017-07-29 10:18:33

标签: java android android-fragments android-background android-thread

我有片段通过Retrofit + RxJava进行API调用。我在Subscription订阅onActivityCreated并在onDestroy处置。当FragmentA仍处理API调用时,我从FragmentB切换到FragmentA时,FragmentB的内容下方会显示FragmentA。这意味着FragmentA内容仍保留在屏幕顶部,并且无法控制它。

FragmentA.java

public class FragmentA extends Fragment {

    @BindView(R.id.swipe_refresh) SwipeRefreshLayout mSwipeRefresh;
    @BindView(R.id.recycler_view) RecyclerView mRecyclerView;

    private ItemsAdapter mAdapter;

    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this, view);

        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                fetchItems();
            }
        });

        mAdapter = new ItemsAdapter();

        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mSwipeRefresh.setRefreshing(true);
        fetchItems();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.clear();
    }

    private void fetchItems() {
        RequestInterface requestInterface = Utils.createService();
        mCompositeDisposable.add(requestInterface.getItemsForA()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Response>() {
                @Override
                public void accept(@NonNull Response response) throws Exception {
                    mAdapter.swapItems(response.getItems());
                    mSwipeRefresh.setRefreshing(false);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(@NonNull Throwable throwable) throws Exception {
                    Toast.makeText(getActivity(), "Error: " + throwable.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    mSwipeRefresh.setRefreshing(false);
                }
            }));
    }
}

FragmentB.java

public class FragmentB extends Fragment {
    //Same as `FragmentA` but different API call
}

我还做了一些日志记录,发现FragmentA包括onDestroyView的所有生命周期方法都被调用了。

1 个答案:

答案 0 :(得分:0)

您需要在SwipeRefreshLayout上调用以下方法来解决此问题。

    swipeRefreshLayout.setRefreshing(false);
    swipeRefreshLayout.destroyDrawingCache();
    swipeRefreshLayout.clearAnimation();
    super.onDestroyView();
}