如何让recyleView,加载的后台数据,在前台图片滚动不卡顿.踩坑,作业.解决,滚动加载慢的问题
程序员文章站
2022-03-07 11:05:24
多的不说.看看下面的代码,用 retrofit2 搭建的. private void load_rvswiper() { townArticleList=new ArrayList<>(); //读取数据接口 分类数据 ApiInterface apiInterface2 = ApiClient.getApiClient()//返回一个 工具 Retrofit .create(ApiInterface.class)...
多的不说.看看下面的代码,
用 retrofit2 搭建的.
private void load_rvswiper() {
townArticleList=new ArrayList<>();
//读取数据接口 分类数据
ApiInterface apiInterface2 = ApiClient.getApiClient()//返回一个 工具 Retrofit
.create(ApiInterface.class); //将retrofit 与 "接口 " retrofit.create()
Call<townNews> call2; //用工具做 retrofit call
call2 = apiInterface2.getTownNews_swiper("scroll");
//下面处理 News call
call2.enqueue(new Callback<townNews>() {//download 获取网上的资源 retrofit 工具
//回调的信息
@Override
public void onResponse(Call<townNews> call, Response<townNews> response) {
//发过来是 New
if (response.isSuccessful() && response.body().getArticles() != null) {
//获取来的 Articles
townArticleList=response.body().getArticles();
rvswiper=findViewById(R.id.Servernews_swiper_rv);
rvswiperAdapter=new homervswiperItemAdapter(townArticleList,home_page.this);
swiperlinearLayoutManager=
// new LinearLayoutManager(home_page.this);
new AutoScrollLayoutManager(home_page.this);
swiperlinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rvswiper.setLayoutManager(swiperlinearLayoutManager );
rvswiper.setAdapter(rvswiperAdapter);
//触发自动滚动
rvswiper.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
rvswiper.smoothScrollToPosition(rvswiperAdapter.getItemCount());
}
});
//连续滚动
rvswiper.setOnScrollListener
(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// 如果自动滑动到最后一个位置,则此处状态为SCROLL_STATE_IDLE
AutoScrollLayoutManager lm = (AutoScrollLayoutManager) recyclerView.getLayoutManager();
int position = lm.findLastCompletelyVisibleItemPosition();
int count = lm.getItemCount();
if (position == count - 1) {
lm.scrollToPosition(0);
rvswiper.smoothScrollToPosition(rvswiperAdapter.getItemCount());
}
}
}
}
);
initListener_swipter();
}
}
@Override
public void onFailure(Call<townNews> call, Throwable t) {
Toast.makeText(home_page.this, "没得到需要新闻结果返回!", Toast.LENGTH_LONG).show();
}
});
//数据读取
}
多的不说.只说说.RV 的滚动原理.
rvswiper.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
rvswiper.smoothScrollToPosition(rvswiperAdapter.getItemCount());
}
});
如果不监测 RV 数据什么时候加载完成就调用.smoothScrollToPosition.性能会很慢.
因为retrofit2的 Call 查询,是一个线程.如果线程还没把数据给 adapter 布置完成
调用 smoothScrollToPosition 会导致.RV 卡住.
本文地址:https://blog.csdn.net/weixin_39306574/article/details/110563769