我正在尝试获取我的点击项目的位置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
.
Your 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();
Update:
getPosition
现在已弃用,您可以使用getLayoutPosition
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)