Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get particular item's view of RecyclerView?

Actually I wanna get view of particular item in RecyclerView in my fragment.class. For this purpose I tried to set a getter in my adapter class then tried to access it in my fragment but I'm unable to access the views .

Code of Adapter Class :

private List<ViewHolder> holder_list=new ArrayList<>();
 @Override
public void onBindViewHolder(ViewHolder holder, int position) {

    holder_list.add(holder);
   }
public ViewHolder getViewHolder(int position){
    return holder_list.get(position);
}

Fragment Code:

MessageAdapter.ViewHolder holder= msgAdp.getViewHolder(msgAdp.getItemCount()-1);
    //Here holder.mMessageView is a text view
Toast.makeText(ctx,holder.mMessageView.getText().toString(),Toast.LENGTH_SHORT).show();
like image 583
anonymous Avatar asked Jan 02 '23 13:01

anonymous


1 Answers

Here is the easiest method

If you want get ViewHolder of item.

RecyclerView.ViewHolder viewHolder = rvList.getChildViewHolder(rvList.getChildAt(0));

or if you want get View object of item.

View view = rvList.getChildAt(0);

Use the one you need. You can get view or ViewHolder. You can manipulate them as you need.

Edit:

getChildAt method is reliable as i also face issue some time, may be it is not yet fixed.

You can use this code

RecyclerView.ViewHolder holder = (RecyclerView.ViewHolder)
recyclerView.findViewHolderForAdapterPosition(position);
if (null != holder) {
   holder.itemView.findViewById(R.id.xyz).setVisibility(View.VISIBLE);
}

Edit 2: Note

This is known issue that if you call findViewHolderForAdapterPosition just after setting list then you get NullPointerException.

if 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.

link

For solving this you can do like this.

recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                RecyclerView.ViewHolder holder = (RecyclerView.ViewHolder)
                recyclerView.findViewHolderForAdapterPosition(position);
                if (null != holder) {
                    holder.itemView.findViewById(R.id.xyz).setVisibility(View.VISIBLE);
                }
            }
        }, 50);
like image 72
Khemraj Sharma Avatar answered Jan 05 '23 19:01

Khemraj Sharma