RecyclerView - findViewHolderForAdapterPosition() returns null for invisible items

时间:2016-10-20 19:05:38

标签: java android android-layout android-recyclerview recycler-adapter

I am trying to update all views on RecyclerView item click. I tried findViewHolderForAdapterPosition() to get the ViewHolder but it returns null for invisible items. I understand that the method can return null if view is not yet prepared and it won't be a wise idea to update other invisible lists if the list is huge. However, my list is very small (always less than 10) and I want to get access to views/viewholders upon an item click.

I am using the following code to update the ViewHolders

        for (int i = 0; i < itemsList.size(); i++) {
            if (i != getAdapterPosition()) {

                MyViewHolder temp = (MyViewHolder) recyclerView.findViewHolderForAdapterPosition(i);

                if (temp != null) {
                    //update elements
                } else {
                    Log.i(TAG, "temp is null");
                }


            }
        }

Any help or leads would be appreciated.

1 个答案:

答案 0 :(得分:0)

I want to get access to views/viewholders upon an item click.

You can simply achieve this functionality by setting onClickListener on any view, inside the onBindViewHolder() method of your adapter.

For dispatching the click event on an item to an activity or fragment for handling :

1- In your adapter class, define an interface called OnItemClickListener :

public interface OnItemClickListener {
     void onItemClicked(int position, AnyOtherDataYouWant data)
}

2- Make your activity or fragment implement this interface

public MyActivity extends AppCompatActivity implements MyAdapter.OnItemClickListener

3- Pass a reference of type OnItemClickListener interface to the constructor of your adapter and save it in an field, called listListener .

4- In the onBindViewHolder of your adapter, on the view you want like a button or a textview :

holder.myview.setOnClickListener(new View.OnClickListener()
{
     @Override
     public void onClick(View view)
    {
         listListener.onItemClicked(position, AnyDataYouWant data) ;
    }
}) ;