在保持滚动位置的同时更新RecyclerView

jam*_*z77 1 android maintainscrollpositionon android-recyclerview

如何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
}
Run Code Online (Sandbox Code Playgroud)

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();
        }
}
Run Code Online (Sandbox Code Playgroud)

完成任务后,我会调用列表进行刷新:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Suh*_* SH 5

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

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

然后设置位置以滚动到:

smoothScroller.setTargetPosition(position);
layoutManager.startSmoothScroll(smoothScroller);
Run Code Online (Sandbox Code Playgroud)