RecyclerView的OnClick位置 [英] RecyclerView OnClick Position

查看:216
本文介绍了RecyclerView的OnClick位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个点击的项目的位置对我的 RecyclerView 。然而,它是一个有点古怪,并且只让我登录的位置单击时,不要让我做一个吐司的位置。在这里看到:

I'm trying to get the position of a clicked item for my RecyclerView. However, it is being a little odd and is only letting me log the position when clicked and not letting me make a Toast of the position. 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 of the position when an item is clicked, the app will crash, but the log seems to work fine. How would I be able to fix it so I can Toast the position of an item when clicked?

推荐答案

我需要看到,你要以确保该错误消息,但它可能是因为你传递了错误的参数到吐司

I'd need to see the error message that you're getting to be sure, but it's probably because you're passing the wrong arguments into the Toast.

吐司是这样的:

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

为getPosition 返回 INT makeText()方法需要一个字符串第二个参数。

getPosition returns an int, and the makeText() method is expecting a String for the second parameter.

更改吐司来的:

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

这篇关于RecyclerView的OnClick位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆