Fix PostFragment's recyclerview lose scroll position after orientation change.

This commit is contained in:
Docile-Alligator
2026-02-06 11:57:14 -05:00
parent d979bb5ca6
commit bc969cf7ed

View File

@ -23,6 +23,7 @@ import androidx.core.view.OnApplyWindowInsetsListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.CombinedLoadStates;
import androidx.paging.LoadState;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
@ -41,6 +42,8 @@ import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import ml.docilealligator.infinityforreddit.FetchPostFilterAndConcatenatedSubredditNames;
import ml.docilealligator.infinityforreddit.Infinity;
import ml.docilealligator.infinityforreddit.PostModerationActionHandler;
@ -210,7 +213,7 @@ public class PostFragment extends PostFragmentBase implements FragmentCommunicat
binding.swipeRefreshLayoutPostFragment.setEnabled(mSharedPreferences.getBoolean(SharedPreferencesUtils.PULL_TO_REFRESH, true));
binding.swipeRefreshLayoutPostFragment.setOnRefreshListener(this::refresh);
int recyclerViewPosition = 0;
int recyclerViewPosition;
if (savedInstanceState != null) {
recyclerViewPosition = savedInstanceState.getInt(RECYCLER_VIEW_POSITION_STATE);
@ -219,6 +222,7 @@ public class PostFragment extends PostFragmentBase implements FragmentCommunicat
concatenatedSubredditNames = savedInstanceState.getString(CONCATENATED_SUBREDDIT_NAMES_STATE);
postFragmentId = savedInstanceState.getLong(POST_FRAGMENT_ID_STATE);
} else {
recyclerViewPosition = 0;
postFilter = getArguments().getParcelable(EXTRA_FILTER);
postFragmentId = System.currentTimeMillis() + new Random().nextInt(1000);
}
@ -715,7 +719,16 @@ public class PostFragment extends PostFragmentBase implements FragmentCommunicat
}
if (recyclerViewPosition > 0) {
binding.recyclerViewPostFragment.scrollToPosition(recyclerViewPosition);
mAdapter.addLoadStateListener(new Function1<>() {
@Override
public Unit invoke(CombinedLoadStates combinedLoadStates) {
if (combinedLoadStates.getRefresh() instanceof LoadState.NotLoading && mAdapter.getItemCount() > 0) {
binding.recyclerViewPostFragment.scrollToPosition(recyclerViewPosition);
mAdapter.removeLoadStateListener(this);
}
return Unit.INSTANCE;
}
});
}
if (mActivity instanceof ActivityToolbarInterface) {