RecyclerView OnClick位置

时间:2015-01-19 03:26:16

标签: android

我正在尝试获取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项目的位置?

1 个答案:

答案 0 :(得分:2)

我需要查看您确定的错误消息,但这可能是因为您将错误的参数传递到Toast

您的Toast看起来像这样:

Toast.makeText(v.getContext(), getPosition(), Toast.LENGTH_LONG).show();

getPosition返回intmakeText()方法预计第二个参数为String

将您的Toast更改为:

Toast.makeText(v.getContext(), "Position: " + getPosition(), Toast.LENGTH_LONG).show();

<强>更新

getPosition现已弃用,您可以使用getLayoutPosition