问题
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.
回答1:
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.
回答2:
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);
}
});
}
}
}
来源:https://stackoverflow.com/questions/35605313/focusing-on-a-recyclerview-item