RecyclerView OnClick Position
I am trying to get the position of the clicked item for mine RecyclerView
. However, this is a bit weird and only allows me to register the position on click and not let me do the Toast
positions. 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
positions when the item is clicked, the app crashes, but the log seems to work fine. How can I fix this so that I can Toast
indicate the position of the element when clicked?
source to share
I will need to see the error message you receive, but this is probably because you are passing the wrong arguments to Toast
.
Yours Toast
looks like this:
Toast.makeText(v.getContext(), getPosition(), Toast.LENGTH_LONG).show();
getPosition
returns int
, and the method makeText()
expects String
for the second parameter.
Change Toast
to this:
Toast.makeText(v.getContext(), "Position: " + getPosition(), Toast.LENGTH_LONG).show();
Update:
getPosition
is now deprecated, you can use getLayoutPosition
source to share