Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking on item programmatically in RecyclerView

I am loading a list of categories and depending on which is selected, I need to show the products of the corresponding category in the RecyclerView. So when I first start the Fragment I need to simulate the user clicking in a default category - in this case, it would be the first one.

How can I perform this?

like image 712
noloman Avatar asked Apr 20 '15 10:04

noloman


3 Answers

Without your code we don't know how you implement your onClickListener.

Normally, you implement and set the item onClickListener in the viewHolder of your RecyclerView.Adapter.
For example: ViewHolder.itemView.setOnClickListener(listener);

So the solution is you can use recyclerView.findViewHolderForAdapterPosition(0).itemView.performClick()

PS: Do not use findViewHolderForLayoutPosition() according to the Doc

like image 137
Xiaoyi LI Avatar answered Nov 13 '22 07:11

Xiaoyi LI


Here is a workaround to select 1st child of RecyclerView after just setting adapter.

//position to be clicked
final int pos = 0;
new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
recyclerView.findViewHolderForAdapterPosition(pos).itemView.performClick();
                    }
                },1);
like image 31
Saurabh Avatar answered Nov 13 '22 06:11

Saurabh


It is frowned upon by purists to use the method

    recyclerView.findViewHolderForAdapterPosition(pos).itemView.performClick();

as it states in docs:

Return the ViewHolder for the item in the given position of the data set. Unlike {@link #findViewHolderForLayoutPosition(int)} this method takes into account any pending adapter changes that may not be reflected to the layout yet. On the other hand, if {@link Adapter#notifyDataSetChanged()} has been called but the new layout has not been calculated yet, this method will return null since the new positions of views are unknown until the layout is calculated. for exactly the reason that delaying with a thread is sometimes useful. Any call to notifyDataSetChanged() causes it to return null. Better to use the adapter method onBindViewHolder and check for position 0. Adjust for how you have set up your listener, the usual way is example here, created in ViewHolder constructor. Use an init variable to prevent it from being called again:

    @Override
    public void onBindViewHolder(FooAdapter.ViewHolder viewHolder, int position) {
     //code
     ...
     //do this last especially if you are using an animator

     if(position == 0 && isInit) {
        listener.onItemClick( viewHolder.itemView,0);
        isInit =false;

     }
  }
like image 13
Droid Teahouse Avatar answered Nov 13 '22 07:11

Droid Teahouse