gpt4 book ai didi

android - 更新 RecyclerView 同时保持其滚动位置

转载 作者:行者123 更新时间:2023-11-29 15:00:35 24 4
gpt4 key购买 nike

更新内容后如何在 RecyclerView 中保留当前滚动位置?

onCreate中,我设置了一个重复任务,如下所示:

private void setRepeatingAsyncTask() {

final Handler handler = new Handler();
Timer timer = new Timer();

TimerTask task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
new getArrivals().execute(station_id);
} catch (Exception e) {
// error, do something
}
}
});
}
};
timer.schedule(task, 0, 30000); // interval of 30 seconds
}

AsyncTask 将查询数据库以获取最新的列表内容:

private class getArrivals extends AsyncTask<Long, Void, Long>{

@Override
protected void onPreExecute(){
//emptyMessage.setVisibility(VISIBLE);
//recyclerView.setVisibility(GONE);
}
@Override
protected Long doInBackground(Long... params) {
long station_id = params[0];
station = db.stationModel().getStationById(station_id);
arrivals = db.arrivalModel().getNextArrivalsByStation(station_id, StaticClass.getDays());
return station_id;
}

@Override
protected void onPostExecute(Long result){
if(getSupportActionBar() != null) {
getSupportActionBar().setTitle(capitalize(station.name));
}

refreshList();
}
}

任务完成后,我会要求刷新列表:

private void refreshList(){

arrivalListAdapter = new ArrivalListAdapter(getApplicationContext(), arrivals);
staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.setAdapter(arrivalListAdapter);
Log.d("arrivals", arrivals.size()+"");
arrivalListAdapter.notifyDataSetChanged();

if(arrivals.size() == 0){
emptyMessage.setVisibility(VISIBLE);
recyclerView.setVisibility(GONE);

new fetchArrivalsFromSource().execute(station.id);
}else{
emptyMessage.setVisibility(GONE);
recyclerView.setVisibility(VISIBLE);
}
}

我很确定问题的原因是我每次都设置适配器。我尝试在初始任务中进行设置,但这导致列表根本没有更新。

最佳答案

您可以获取当前位置,刷新适配器并平滑滚动到上一个位置,如下所示:

RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};

然后设置滚动到的位置:

smoothScroller.setTargetPosition(position);
layoutManager.startSmoothScroll(smoothScroller);

关于android - 更新 RecyclerView 同时保持其滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46573973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com