8

I am trying to focus on a particular item of a recyclerview. What is the equivalent of the listview.setSelection(position) when using a recyclerview.

Alex Kombo
  • 3,256
  • 8
  • 34
  • 67

2 Answers2

19

You call RecyclerView.scrollToPosition(position) to request the RecyclerView's LayoutManager to scroll to the given position during the next layout pass (it's asynchronous).

To request focusing an item view, the view must be focusable and you call View.requestFocus(). If the view is not yet laid out at the time you want to focus it, you can call View.requestFocus() as soon as onViewAttachedToWindow() has been called.

BladeCoder
  • 12,779
  • 3
  • 59
  • 51
  • 1
    When would you call requestFocus in the item view to correspond with the RecyclerView being scrolled to that item? – B W Jan 04 '18 at 21:25
  • 2
    You would call it in `Adapter.onViewAttachedToWindow()`, when the ViewHolder is the one matching your item. You can check `ViewHolder.getAdapterPosition()`. – BladeCoder Jan 05 '18 at 03:34
-3

In this example, there is a ImageView and I set it OnClickListner. You have to do like that in your ViewHolder class:

public class ViewHolder extends RecyclerView.ViewHolder {

    public ViewHolder(View itemView, int viewType) {
        super(itemView);
    }

    public void setImage(String imagePath) {
        ImageView imageView = (ImageView) itemView.findViewById(R.id.images);
        if (null == imageView) return;
        final File file = new File(imagePath);
        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            imageView.setImageBitmap(bitmap);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(context, FullScreenImageActivity.class);
                    i.putExtra("image_path", file.getAbsolutePath());
                    context.startActivity(i);
                }
            });
        }
    }
}
Akbar
  • 430
  • 4
  • 18