0

I'm searching on how can I save and restore the recycler view position for my app (never tried to implement saving and restoring the position of recycler view) and after seeing many different ways to implement I found an interesting way wherewith recyclerview:1.2.0-alpha02 it is done automatically here is a medium article

I have read the article but I didn't know how to exactly implement it in my code

please forgive me for the very unprofessional way I'm writing this because I really don't know how to implement a recycler view that saves the scroll and restores the position

The functionality I want for saving and restoring position is kind of Instagram or youtube or any big social media or app with endless scroll where if u switch between different activities or fragments still the position of the recycler view is maintained when you came back

Here is the code // the code is without any implementation of recyclerview:1.2.0-alpha02 because as I said above I don't know how to implement it

Note:- If anyone wants more references of my code please tell me I will update the question and I have used StaggeredGridLayoutManager just mentioning it, in case if it is necessary to know

Home_Fragment.java

private final boolean loading = true;
    private final String KEY_RECYCLER_STATE = "recycler_state";
    public List<Upload> mUploads;
    PostAdapter_Home postsAdapter;
    ShimmerFrameLayout shimmerFrameLayout;
    private RecyclerView postRecyclerView;
    //    private Parcelable listState;
    private int pastVisibleItems, visibleItemCount, totalItemCount;
    //    Boolean isScrolling = false;
//    int currentItems, totalItems, scrolledOutItems;

    @SuppressLint("SourceLockedOrientationActivity")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        requireActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        MaterialToolbar materialToolbar = view.findViewById(R.id.toolbar);
        materialToolbar.setOnMenuItemClickListener(toolbarItemClickListener);
        postRecyclerView = view.findViewById(R.id.recyclerViewHome);
        shimmerFrameLayout = view.findViewById(R.id.shimmerEffect);
//        this is for one item per scroll
//        SnapHelper snapHelper = new PagerSnapHelper();
//        snapHelper.attachToRecyclerView(verticalRecyclerView);
        postRecyclerView.setAdapter(postsAdapter);
//        listState = savedInstanceState.getParcelable("ListState");

        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        postRecyclerView.setLayoutManager(
                staggeredGridLayoutManager // I have 3 rows
        );


//        postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
//
//                visibleItemCount = staggeredGridLayoutManager.getChildCount();
//                totalItemCount = staggeredGridLayoutManager.getItemCount();
//                int[] firstVisibleItems = null;
//                firstVisibleItems = staggeredGridLayoutManager.findFirstVisibleItemPositions(firstVisibleItems);
//                if (firstVisibleItems != null && firstVisibleItems.length > 0) {
//                    pastVisibleItems = firstVisibleItems[0];
//                }
//
//                if (loading) {
//                    if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
//                        loading = false;
//                        getData();
//                        Log.d("tag", "LOAD NEXT ITEM");
//                    }
//                }
//            }
//        });
//        setupFirebaseAuth();
        getData();
        shimmerFrameLayout.startShimmer();
        mUploads = new ArrayList<>();
        postsAdapter = new PostAdapter_Home(getContext(), mUploads);
        postRecyclerView.setAdapter(postsAdapter);
        postRecyclerView.scrollToPosition(Home_Fragment.saved_position);
        return view;
    }


    private void getData() {
        databaseReference.addValueEventListener(new ValueEventListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    shimmerFrameLayout.stopShimmer();
                    shimmerFrameLayout.setVisibility(View.GONE);
                    postRecyclerView.setVisibility(View.VISIBLE);
                    mUploads.clear();
                    for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                        Upload upload = dataSnapshot.getValue(Upload.class);
                        assert upload != null;
                        upload.setmKey(dataSnapshot.getKey());
                        mUploads.add(upload);


                    }

                }

                //notify the adapter
                postsAdapter.notifyDataSetChanged();
//                loading = true;
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
//                loading = true;
            }
        });
    }

PostAdapter_Home.java

public class PostAdapter_Home extends RecyclerView.Adapter<PostAdapter_Home.PostViewHolder> {
    public static List<Upload> mUploads;
    public Context mcontext;

    public PostAdapter_Home(Context context, List<Upload> uploads) {
        mUploads = uploads;
        mcontext = context;
    }


    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        view = LayoutInflater.from(mcontext).inflate(R.layout.ex_home, parent, false);
        return new PostViewHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        Shimmer shimmer = new Shimmer.ColorHighlightBuilder()
                .setBaseColor(Color.parseColor("#F3F3F3"))
                .setBaseAlpha(1)
                .setHighlightColor(Color.parseColor("#E7E7E7"))
                .setHighlightAlpha(1)
                .setDropoff(50)
                .build();
        ShimmerDrawable shimmerDrawable = new ShimmerDrawable();
        shimmerDrawable.setShimmer(shimmer);
        Upload uploadCurrent = mUploads.get(position);
        Glide.with(mcontext)
                .load(uploadCurrent.getmImageUrl())
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .placeholder(shimmerDrawable)
                .centerCrop()
                .fitCenter()
                .into(holder.imageView);

//        holder.imageView.setOnClickListener(view -> changeScaleType(holder, position));

    }

    @Override
    public int getItemCount() {
        return mUploads.size();
    }

    public static class PostViewHolder extends RecyclerView.ViewHolder {

        private final ShapeableImageView imageView;

        public PostViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imagePostHome);

        }


    }
}

Vasant Raval
  • 257
  • 1
  • 12
  • 31
  • I have implemented recycler view androidx.recyclerview:recyclerview:1.2.1 in my own app and i dont see any difference between yours and mine recycler view code. – Danish Oct 23 '21 at 18:36
  • And yes there is no change in scrolling position if i swipe from one fragment to other or if i move from one activity to other.I havent implemented any staterestorationpolicy in my app. – Danish Oct 23 '21 at 18:37
  • Ok but I have to implement that save and restore functionality in my recyclerview and with this recyclerview alpha 2 it is done automatically how can I do that – Vasant Raval Oct 24 '21 at 05:26
  • Why woud you use recyclerview alpha02 if you have stable release recyclerview1.2.1?Try implementing your recyclerview as you usually do. – Danish Oct 24 '21 at 05:51
  • Ok but how do I implement it in my code that's the point I want that functionality of automatic save and restoring the position , how do I do that with my code with recyclerview 1.2.1 – Vasant Raval Oct 24 '21 at 06:06

0 Answers0