After almost a day of struggling with this method to save and retrieve the position of the last viewed item, I finally found a solution that gives me the desired output. After opening one of my items on the way back to the RecyclerView my app scrolls to that item but with a small bug... I am using 2 methods onPause() and onResume() and this is my implementation:
@Override
protected void onPause() {
super.onPause();
lastFirstVisiblePosition = ((LinearLayoutManager)
mRecyclerView.getLayoutManager()).findLastVisibleItemPosition();
Log.d("position", String.valueOf(lastFirstVisiblePosition));
}
@Override
protected void onResume() {
super.onResume();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mRecyclerView.scrollToPosition(lastFirstVisiblePosition);
}
}, 200);
}
- Since I am a beginner I am not sure if using the Handler in this purpose is a smart idea?
- Because my cards/items are not the same sizes I am not able to return to the position of the last viewed item as long as the item is not in a certain position meaning as long as the item below is not on the screen... Is there any way to consider the dimension of my card and according to that set the position?
one more thing to add I had tried onSaveInstanceState() and onRestoreInstanceState() methods but unsuccessfully... One of the implementations:
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
lastFirstVisiblePosition = ((LinearLayoutManager)
mRecyclerView.getLayoutManager()).findLastVisibleItemPosition();
outState.putString("position", String.valueOf(lastFirstVisiblePosition));
Log.d("currentPos", String.valueOf(outState));
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String position = savedInstanceState.getString("position");
mRecyclerView.scrollToPosition(Integer.parseInt(position));
}
in this way, I was able to get the current position but not to restore it...