How to save scroll position of recyclerview in fragment

Viewed 7178

I have followed so many answers from here.. but not a single one solving my issue .. that's why i am asking.

I want to save scroll position in a fragment. In So many articles they have suggested to follow

@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

and

@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

But this two method is not available in fragment.

My code:

private int mPositionIng = RecyclerView.NO_POSITION;

private String KEY_POSITION_ING = "KeyPositionIng";

in OnCreateView()

if (savedInstanceState != null) {

            if (savedInstanceState.containsKey(KEY_POSITION_ING)) {
                mPositionIng = savedInstanceState.getInt(KEY_POSITION_ING);
            }
}

Override Methods in fragment They are not same method as above. i don't know where i am doing wrong.

@Override
    public void onSaveInstanceState(Bundle outState) {

        int scrollPositionIng = mRecyclerViewIngredients.computeVerticalScrollOffset();

        mPositionIng = scrollPositionIng;

        outState.putInt(KEY_POSITION_ING, mPositionIng);
        super.onSaveInstanceState(outState);
    }

@Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {

        if (mPositionIng != RecyclerView.NO_POSITION) {

            mRecyclerViewIngredients.getLayoutManager().scrollToPosition(mPositionIng);
        }


        super.onViewStateRestored(savedInstanceState);
    }

I just need to save scroll position while the orientation changes .. Please help. Any Suggestion will be help full. Thanks......

3 Answers

Let the Android OS handle that for you, in AndroidManifest.xml inside your wanted tag activity add:

android:configChanges="orientation|screenSize"

for future coders

I guess when you came back to your fragment you lost position this is because the values stored in the recycler view of the fragment is lost. If you keep code in start or other methods in fragment their scope is lost.

keep your code in On Create View in fragment because scope will not be lost it will work maximum times if not try by declaring all variables in class not in local method and initialize in oncreateview method. how to get context in on create view?? you can google

Related