如何在RecyclerViewAdapter中更新数据时停止向上滚动屏幕?

时间:2016-09-09 09:32:53

标签: android scroll android-recyclerview

我有RecyclerView和一些视图。它们每秒都在实现。问题是,当用户向下滚动时,屏幕每秒向上滚动(刷新)。如何在数据更新后使其保持位置? 这是我的代码:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView)findViewById(R.id.mainRecyclerView);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    initializeData();
    adapter = new RecyclerViewAdapter(offers);
    startCount();

}
private void startCount(){
    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            updateData();
            handler.postDelayed(this, 1000);

        }
    };
    handler.postDelayed(runnable, 1000);


}
private void initializeData(){
    offers = new ArrayList<>();
    seconds = new ArrayList<>();
    seconds.add(600);
    seconds.add(10);
    seconds.add(20);
    offers.add(new Offer(seconds.get(0), R.drawable.zdj, 200));
    offers.add(new Offer(seconds.get(1), R.drawable.zdj));
    offers.add(new Offer(seconds.get(2), R.drawable.zdj));

}


private void updateData(){
    int i = 0;
    int tempSec;
    for(int j = 0; j < seconds.size();j++){

        tempSec = seconds.get(j);
        if(tempSec==0){
            offers.remove(j);
            seconds.remove(j);
            break;
        }
        tempSec--;
        seconds.set(j, tempSec);
        offers.set(j, new Offer(seconds.get(j), R.drawable.zdj));
    }
    initializeAdapter();
}
private void initializeAdapter() {

    adapter.notifyItemChanged(offers.size());
    recyclerView.setAdapter(adapter);
}

1 个答案:

答案 0 :(得分:0)

您必须更新RecyclerView的特定行。请根据您的要求使用以下任一方法,

notifyItemChanged(int position, Object payload)

notifyItemChanged(int position)

您还可以设置要显示的位置的特定位置。