我正在尝试获取 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
项目的位置?
最佳答案
我需要查看您要确定的错误消息,但这可能是因为您将错误的参数传递到 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
关于android - RecyclerView OnClick 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28017547/