我正在尝试获取RecyclerView
点击项目的位置。但是,它有点奇怪,只是让我在点击时记录位置,而不是让我做出Toast
的位置。见这里:
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();
}
}
如果我在单击某个项目时取消注释该位置的Toast
,则该应用程序将崩溃,但该日志似乎正常工作。我如何能够解决这个问题,以便点击时可以Toast
项目的位置?
答案 0 :(得分:2)
我需要查看您确定的错误消息,但这可能是因为您将错误的参数传递到Toast
。
您的Toast
看起来像这样:
Toast.makeText(v.getContext(), getPosition(), Toast.LENGTH_LONG).show();
getPosition
返回int
,makeText()
方法预计第二个参数为String
。
将您的Toast
更改为:
Toast.makeText(v.getContext(), "Position: " + getPosition(), Toast.LENGTH_LONG).show();
<强>更新强>
getPosition
现已弃用,您可以使用getLayoutPosition