我有片段通过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
的所有生命周期方法都被调用了。
答案 0 :(得分:0)
您需要在SwipeRefreshLayout
上调用以下方法来解决此问题。
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.destroyDrawingCache();
swipeRefreshLayout.clearAnimation();
super.onDestroyView();
}