android - RecyclerView OnClick 位置

标签 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 项目的位置?

最佳答案

我需要查看您要确定的错误消息,但这可能是因为您将错误的参数传递到 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/

相关文章:

android - 如何实现对可运行线程的简单 RxJava 调用?

android - 如何在 Android 中获取相对于另一个 View 的 View 位置?

android - 可绘制资源文件夹中的子文件夹?

Android Studio 无法让模拟器运行

android - 将 CookieHandler 与 OkHttp 和 Retrofit 2 一起使用

java - 在后台检查互联网

java - 当所有数据结构都具有有效值时,数组列表和三个数组的客户适配器不会填充 ListView

android - 使用 android :imeOptions ="actionNext" in Table Layout 时出现问题

android - 使用 GCM 推送通知和相应的聊天 Activity

Android:捕获 BLE 连接失败/断开连接?