Adapter for RecyclerView

时间:2016-07-20 18:38:35

标签: android android-recyclerview recycler-adapter

在我的RecyclerView适配器中,我试图在每行单击文本时发送文本,但是我收到了上下文错误。我是初学程序员,所以我不知道该怎么做。提前致谢。此外,我正在尝试创建一个应用程序,其中每行都有一个消息组聊天,每个人都可以看到,每个用户都可以添加一行,他们选择任何标题。如果有人可以帮助我,那就太棒了!非常感谢,因为我很新手。谢谢!

我得到的错误发生在我举杯的地方。

更便宜的代码:

package com.example.patri.index01;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private LayoutInflater inflater;
List<Information> data= Collections.emptyList();

public MyAdapter(Context context, List<Information> data){
    inflater=LayoutInflater.from(context);
    this.data=data;

}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view=inflater.inflate(R.layout.custom_row, parent,false);
    MyViewHolder holder=new MyViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {

    Information current=data.get(position);

    holder.title.setText(current.title);
    holder.icon.setImageResource(current.iconId);

    holder.title.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(context, "Item clicked at " +position, Toast.LENGTH_SHORT)
        }
    });


}

@Override
public int getItemCount() {
    return data.size();
}

class MyViewHolder extends RecyclerView.ViewHolder{
    TextView title;

    ImageView icon;

    public MyViewHolder(View itemView) {

        super(itemView);

        title= (TextView)itemView.findViewById(R.id.listText);

        icon= (ImageView) itemView.findViewById(R.id.listIcon);

    }
}
}

信息类:

public class Information {

int iconId;

String title;

}

2 个答案:

答案 0 :(得分:1)

问题正在发生,因为在context类构造函数中传递的onClick方法中无法访问MyAdapter

onClick方法中使用v.getContext()

  Toast.makeText(v.getContext(), "Item clicked at " +position, Toast.LENGTH_SHORT)

OR

context类中声明MyAdapter并在构造函数中初始化它:

Context context;
public MyAdapter(Context context, List<Information> data){
    this.context=context;
    inflater=LayoutInflater.from(context);
    this.data=data;

}

答案 1 :(得分:0)

Toast.makeText(context, "Item clicked at " +position, Toast.LENGTH_SHORT)更改为Toast.makeText(v.getContext(), "Item clicked at " + position, Toast.LENGTH_SHORT).show();