eliftekin
eliftekin

Reputation: 13

How to save recyclerview item expanded/collapsed state in java

I've been working on a app. It has a recyclerview that displays the items that are fetched from api. each list item can be expanded. it works fine but when i rotate the device the expanded item goes back to its default state. my question is how can i save its state when the device is rotated. I've tried to save the recyclerview's state using onSaveInstanceState and onRestoreInstanceState. but it didnt help me to save the list item's state. i put what i tried in below

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

    RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
    if (layoutManager != null) {
        outState.putParcelable("recycler_state", layoutManager.onSaveInstanceState());
    }
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    Parcelable savedRecyclerState = savedInstanceState.getParcelable("recycler_state");
    recyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerState);
}

Upvotes: 1

Views: 58

Answers (0)

Related Questions