2017-10-04 112 views
0

如何在更新内容后将当前滚动位置保持在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 
} 

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); 
    } 
} 

我在前确信我的问题的原因是我每次都设置适配器。我试着用最初的任务设置它,但是导致列表没有被更新。

回答

5

您可以获得当前的位置,刷新适配器和平滑滚动到以前的位置是这样的:

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

然后设置位置滚动到:

smoothScroller.setTargetPosition(position); 
layoutManager.startSmoothScroll(smoothScroller); 
相关问题