user3008777
user3008777

Reputation: 1441

What is the equivalent listview.setSelection in case of Recycler View

In the case of a ListView if we want to make a particular item selected we use the setSelection method. How do we do this in case of RecyclerView?

Upvotes: 37

Views: 22925

Answers (4)

Libin
Libin

Reputation: 17085

Use RecyclerView LayoutManager to scroll item at position

recyclerView.getLayoutManager().scrollToPosition(position)

Upvotes: 29

HaimS
HaimS

Reputation: 824

ListView.setSelected() does (at least) two things:

  1. It sets the item in the list to be selected (while removing the selection from another item - if such exists)
  2. It scrolls the list so that the item will be visible on the screen.

To achieve 2. either call scrollToPosition() method of RecyclerView (as indicated by Loser), or call one of the scrolling methods of the LayoutManager object depending on your desired scrolling behavior.

For example, recyclerView.getLayoutManager().smoothScrollToPosition()

You may want to scroll the minimum so that the selected item shows on the screen. If so and you are using LinearLayoutManager or GridLayoutManager, you can build such scroll logic based on findFirstCompletelyVisibleItemPosition() and findLastCompletelyVisibleItemPosition() defined in these classes.

Achieving 1. is more tricky. You may want to use the following recipe:

First define a background color in colors.xml, item_state_selected_color, to be used when an item is selected. In your onCreateViewHolder() implementation create a StateListDrawalbe and set it as the background of the view. Say something like this:

public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

    // inflate the item view
    View itemView =  LayoutInflater.from(viewGroup.getContext()).
                           inflate(itemResourceId,viewGroup, false);

    // create color drawable by a resorce id
    ColorDrawable colorDrawableSelected =
       new ColorDrawable(resources.getColor(R.color.item_state_selected_color)); 

   // create StateListDrawable object and define its states
   StateListDrawable stateListDrawable = new StateListDrawable();
   stateListDrawable.addState(new int[]{android.R.attr.state_selected}, colorDrawableSelected);
   stateListDrawable.addState(StateSet.WILD_CARD, null);

   // set the StateListDrawable as background of the item view
   if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
      itemView.setBackgroundDrawable(stateListDrawable); 
   }
   else {
      itemView.itemView.setBackground(stateListDrawable);
   }

   // create view holder object providing it with the item view
   return new YourViewHolder(itemView);   
}

In YourAdapter object (or elsewhere) save a variable, mCurrentSelectedPosition (probably initialized to -1) that holds the current selected position. Still in the adapter, define handler for clicks on recycler view items, depending on your click logic. For example:

void onItemClick(int position) {

   YourViewHolder yourViewHolder;

   int oldSelectedPosition = mCurrentSelectedPosition;

   if (position != mCurrentSelectedPosition) {
      mCurrentSelectedPosition = position;

      if (oldSelectedPosition != -1) {
         yourViewHolder = findViewHolderForPosition(oldSelectedPosition); 
         yourViewHolder.itemView.setSelected(false);     
      } 

      yourViewHolder = findViewHolderForPosition(mCurrentSelectedPosition);
      yourViewHolder.itemView.setSelected(true);
   }        
}

Next, in the constructor of YourViewHolder set listener to clicks on the item:

public YourViewHolder(View itemView,YourAdapter adapter) { 
  mAdapter = adapter;

  // ... other code here ...

  itemView.setOnClickListener(this);
}

Still in YourViewHolder override the onClick() method to delegate handling to the adapter. like this

@Override
public void onClick(View v) {
   mAdapter.onItemClick(getPosition());
}

Now there is just last problem to solve - we need to keep track of the selected item with respect to recycling.

@Override
public void onBindViewHolder(YourViewHolder yourViewHolder, int position) {

  if (position == mCurrentSelectedPosition) {
     yourViewHolder.itemView.setSelected(true);
  }
  else { 
     yourViewHolder.itemView.setSelected(false);
  }     

  // ... other code here ...  
}

Good luck!

Upvotes: 4

Reaz Murshed
Reaz Murshed

Reputation: 24211

Check

recyclerView.scrollToPosition(cursor.getcount() - 1);

Upvotes: 7

Pramod
Pramod

Reputation: 1133

Check

scrollToPositionWithOffset(int position, int offset)
scrollToPositionWithOffset(5,0);

from LinearLayoutManager Scroll to the specified adapter position with the given offset from resolved layout start.

pass offset as 0 if you want selection at top

This worked for me

Upvotes: 22

Related Questions