0

I am coding an Android application for a school project.

I have implemented a RecyclerView with horizontal scroll using LinearLayoutManager.HORIZONTAL.

I would like to make it such that a specific element, for example element n, is in the middle of the set of currently visible elements, like so: enter image description here

I have searched around, and found this link: https://www.reddit.com/r/androiddev/comments/3o0xzw/how_do_you_scroll_to_an_item_with_recyclerview_to/

The solution involved taking half the sum of layoutManager.findFirstVisibleItemPosition() and layoutManager.findLastVisibleItemPosition() and adding it to the position of the element you want to be in the middle.

However, these two methods always returned RecyclerView.NO_POSITION when I used this horizontally scrolling RecyclerView, hence half the sum would be 0, and it would render the calculation useless.

Here is my code:

RecyclerView selectDay = (RecyclerView) findViewById(R.id.lv_selectDay);
    daySelectorAdapter adapter = new daySelectorAdapter(this, arrayList);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    selectDay.setAdapter(adapter);
    selectDay.setLayoutManager(layoutManager);

    int firstVisible = layoutManager.findFirstVisibleItemPosition();
    Log.d("FIRSTVISIBLE", String.valueOf(firstVisible)); // returns -1

    int lastVisible = layoutManager.findLastVisibleItemPosition();
    Log.d("LASTVISIBLE", String.valueOf(lastVisible)); // also -1

    int halfScreenOffset = (lastVisible - firstVisible) / 2;
    Log.d("HALFOFFSET", String.valueOf(halfScreenOffset));

    layoutManager.scrollToPositionWithOffset((15 + halfScreenOffset), 0);

May I know if anyone has a workaround to this problem? Thanks in advance.

EDIT: When I tried implementing a onScrollListener and cast recyclerView.getLayoutManager() to LinearLayoutManager, these methods worked perfectly fine. May I know why?

EDIT 2:

I used this solution right here: RecyclerView smoothScroll to position in the center. android, However why do the methods return NO_POSITION?

Ruan_Lopes
  • 1,243
  • 12
  • 18
meeps
  • 59
  • 7

0 Answers0