Tehleel Mir
Tehleel Mir

Reputation: 853

How can i save the scroll position in a recycler view after every time i recreate it?

below is the method which is called every time a button is clicked and it creates a list with new data

public void fire(View v) {
    String temp = editText.getText().toString();

    myRecyclerView = new MyRecyclerView(this, 500, temp);
    recyclerView.setAdapter(myRecyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    myRecyclerView.setClickListener(this);
} 

how can I save the scroll position so that when next time the button is clicked, list remains on the same position

Upvotes: 0

Views: 50

Answers (1)

janithcooray
janithcooray

Reputation: 308

Well, use this every time you re-create it.

linearLayoutManager.scrollToPositionWithOffset(pos, 0);     

Code:

public void fire(View v) {
    String temp = editText.getText().toString();

    myRecyclerView = new MyRecyclerView(this, 500, temp);
    recyclerView.setAdapter(myRecyclerView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(linearLayoutManager);
    myRecyclerView.setClickListener(this);
    //assuming th layout is loaded. set pos as the position you want to scroll to
    int pos=0;
    linearLayoutManager.scrollToPositionWithOffset(pos, 0); 

} 

Upvotes: 1

Related Questions