user3358306 user3358306 -5 years ago 281
Android Question

RecyclerView OnClick Position

I'm trying to get the position of a clicked item for my

. However, it is being a little odd and is only letting me log the position when clicked and not letting me make a
of the position. See here:

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder>{

private List<Country> countries;
private int rowLayout;
private Context mContext;

public MainAdapter(List<Country> countries, int rowLayout, Context context) {
this.countries = countries;
this.rowLayout = rowLayout;
this.mContext = context;

public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView countryName;

public ViewHolder(View itemView) {
countryName = (TextView) itemView.findViewById(;

itemView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("RecyclerView", "onClick´╝Ü" + getPosition());
//Toast.makeText(v.getContext(),getPosition(), Toast.LENGTH_LONG).show();



public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new ViewHolder(v);


public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Country country = countries.get(position);

public int getItemCount() {
return countries == null ? 0 : countries.size();

If I uncomment the
of the position when an item is clicked, the app will crash, but the log seems to work fine. How would I be able to fix it so I can
the position of an item when clicked?

Answer Source

I'd need to see the error message that you're getting to be sure, but it's probably because you're passing the wrong arguments into the Toast.

Your Toast looks like this:

Toast.makeText(v.getContext(), getPosition(), Toast.LENGTH_LONG).show();

getPosition returns an int, and the makeText() method is expecting a String for the second parameter.

Change your Toast to this:

Toast.makeText(v.getContext(), "Position: " + getPosition(), Toast.LENGTH_LONG).show();


getPosition is deprecated now, You can use getLayoutPosition

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download