Nawaz Nawaz - 1 month ago 18
Android Question

getAdapterPosition not working (v24)

I am using on bind view holder though but for some reasons I am getting the 'cannot resolve method error".
As you can see this is my first attempt so I might be committing some huge mistake.
I have tried multiple methods but none of them seems to work.

package com.techhgeeks.techhgeeks;
import android.support.v7.widget.RecyclerView;
import android.content.Context;
import android.widget.ImageView;
import android.widget.TextView;


import android.view.LayoutInflater;
import java.util.List;
import com.bumptech.glide.Glide;
import android.view.View;
import android.view.ViewGroup;




public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener {
private Context context;
private List<MyData> my_data;

public MyAdapter(Context context, List<MyData> my_data) {
this.context = context;
this.my_data = my_data;
}



@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_child,parent,false);

return new ViewHolder(itemView);
}

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

holder.description.setText(my_data.get(position).getDescription());
Glide.with(context).load(my_data.get(position).getImage_link()).into(holder.imageView);

}

@Override
public int getItemCount() {
return my_data.size();
}

@Override
public void onClick(View view) {
int position = getAdapterPosition();

}


public class ViewHolder extends RecyclerView.ViewHolder{

public TextView description;
public ImageView imageView;

public ViewHolder(View itemView) {
super(itemView);
description = (TextView) itemView.findViewById(R.id.textView);
imageView = (ImageView) itemView.findViewById(R.id.image);
}


}


}

Answer

I found the problem which is because that you are using the getAdapterPosition in the wrong place.

First, remove this part in the original code (onClick):

int position = getAdapterPosition();

Second, modify the onCreateViewHolder method.

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_child, parent, false);
    final ViewHolder holder = new ViewHolder(itemView);
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = holder.getAdapterPosition();
        }
    });
    return new ViewHolder(itemView);
}