3

I understand there were some discussions regarding what I tried to resolve on SO. Here are a couple that I've found so far: this and this.

The suggestions worked for me to some extend but unfortunately didn't resolve the whole problem of mine. Let me elaborate:

Simply put I have a list of items that I put in a RecyclerView and I wanted to scroll to a certain item after I clicked a button on the top menu bar. To simply things, I just wanted to scroll to the last item when clicked, for now.

I tried to put the code right after retrieving the reference to RecyclerView, like this (listView is a RecyclerView):

    listView = (RecyclerView) mRoot.findViewById(R.id.list_section);
    listView.setHasFixedSize(true);
    LinearLayoutManager mListViewManager = new LinearLayoutManager(getActivity());
    listView.setLayoutManager(mListViewManager);
    listView.scrollToPosition(entries.size()-1);

This worked. However, if I tried to do the following, it didn't, please pay attention to the comments below:

 //enter this block when the menu item was clicked
 public boolean onOptionsItemSelected(MenuItem item) {
     //mPagerAdapter is a reference to a FragmentStatePagerAdapter extended class
     mPagerAdapter.highlightPosition(list.size()-1);
 }

//selSchedListFragment is a reference to a Fragment extended class
public void highlightPosition(int pos){
  selSchedListFragment.highlightPosition(pos);
};

and inside the Fragment class is how highlightPosition is defined:

public void highlightPosition(int pos) {
    //listView.getLayoutManager().scrollToPosition(pos);
    listView.smoothScrollToPosition(pos);
    //listView.scrollToPosition(pos);
    //LinearLayoutManager llm = (LinearLayoutManager) listView.getLayoutManager();
    //llm.scrollToPositionWithOffset(pos , 29);

}

You will notice that I tried a few techniques in the core function of highlightPosition, but none worked.

There must be something that is missing, can anyone please suggest.

Community
  • 1
  • 1
J.E.Y
  • 1,173
  • 2
  • 15
  • 37

3 Answers3

0

In onOptionsItemSelected method do

mPagerAdapter.highlightPosition(listView.getAdapter().getItemCount() - 1);
Lingeshwaran
  • 579
  • 4
  • 15
0

For scrolling in listview you can use the native functions

For a direct scroll:

getListView().setSelection(21);

For a smooth scroll:

listview.smoothScrollToPosition(21);
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
pankaj yadav
  • 424
  • 4
  • 10
0

This works for me to move the recycler view focus to last row

 mRecyclerView.getLayoutManager().smoothScrollToPosition(mRecyclerView,null, finalCustomItems.size()-1);
Alok Gupta
  • 1,806
  • 22
  • 21