keep the same position of a recyclerView when going back

3

I have a question as to how I can return to the same position as my recyclerView, since when I return from another activity it sends me to the beginning and I would like to keep the same position in which I left it. It should be noted that I am using a GridLayout and that said recycler is within a fragment, is it possible to return to the same position as the last view? thanks.

recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
        layoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new Adapter();
        recyclerView.setAdapter(adapter);
    
asked by Gunnar 09.04.2016 в 16:23
source

1 answer

1

If you load another activity, you can save the position when the onPause() method of the initial activity is executed.

Add 2 methods to your adapter, to obtain and store the position:

    public int getSelectedPosition() {
        return selectedPosition;
    }

    public void setSelectedPosition(int selectedPosition) {
        this.selectedPosition = selectedPosition;
    }

to get the position you can do it with .getSelectedPosition() of your Adapter.

@Override
    public void onPause() {
        if (miAdapter != null) {
            selectedPosition = miAdapter.getSelectedPosition();
        }
        super.onPause();
    }

When you return, simply move to the position of your adapter.

miAdapter.setSelectedPosition(selectedPosition);

If you want to keep the position when you rotate your application you can save the position through onSaveInstanceState() for example:

@Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("miPosicion", selectedPosition);
        super.onSaveInstanceState(outState);
    }

and within onCreate() retrieves the position:

public void onCreate(Bundle savedInstanceState) {
...
...
selectedPosition = savedInstanceState.getInt("miPosicion");
...
..

Move your Adapter to the saved position:

miAdapter.setSelectedPosition(selectedPosition);
    
answered by 10.04.2016 / 02:10
source