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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With