[英]Update RecyclerView while keeping its scroll position
更新內容后如何在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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.