Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getAdapterPosition in onCreateViewHolder is always "-1"

in many questions, people say "call OnClickListener in onCreateViewHolder. you don't need call OnClickListener each item in onBindViewHolder"

@Override
  public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
     View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
     final ViewHolder holder = new ViewHolder(v);

     holder.itemView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             Log.d(TAG, "position = " + holder.getAdapterPosition());
         }
     });
     return new Viewholder(v);
  }

  @Override
  public void onBindViewHolder(final BoardListViewHolder holder, int position) {

  }

but in Logcat, always show "position = -1"

this is not correct.

why i should call onClickListener in onCreateViewHolder?

like image 960
01hanst Avatar asked Jan 11 '18 08:01

01hanst


2 Answers

getAdapterPosition in onCreateViewHolder is always “-1”

You should return holder instead of new Viewholder(v) .

Code Structure

@Override
  public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
     View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
     final ViewHolder holder = new ViewHolder(v);

     holder.itemView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             Log.d(TAG, "position = " + holder.getAdapterPosition());
         }
     });
     return holder;
  }

  @Override
  public void onBindViewHolder(final BoardListViewHolder holder, int position) {

  }
like image 174
IntelliJ Amiya Avatar answered Nov 15 '22 07:11

IntelliJ Amiya


onCreateViewHolder is used to inflate the layout resource only and you shouldn't put any methods related to your holder items here.

Instead, you have to use onBindViewHolder to get the value of holder.getAdapterPosition or set onClickListeners etc. there.

like image 40
Patryk Goworowski Avatar answered Nov 15 '22 07:11

Patryk Goworowski