user3358306 user3358306 - 5 months ago 64
Android Question

RecyclerView OnClick Position

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

RecyclerView
. However, it is being a little odd and is only letting me log the position when clicked and not letting me make a
Toast
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) {
super(itemView);
countryName = (TextView) itemView.findViewById(R.id.countryName);

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

}


}


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

}


@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Country country = countries.get(position);
viewHolder.countryName.setText(country.name);
}


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


If I uncomment the
Toast
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
Toast
the position of an item when clicked?

Answer

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();

Update:

getPosition is deprecated now, You can use getLayoutPosition

Comments