android - 如何在AdapterClass中使用RecyclerView

时间:2017-01-31 04:40:37

标签: java android android-recyclerview

我需要我的RecyclerView图片可以按下并转到下一个活动。我有Adapter代码。

public class MakananAdapter extends RecyclerView.Adapter<MakananAdapter.ViewHolder> {
ArrayList<Makanan> makananList;

public MakananAdapter(ArrayList<Makanan> makananList)
{
    this.makananList = makananList;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,parent,false);
    ViewHolder vh = new ViewHolder(v);
    return vh;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Makanan tanaman = makananList.get(position);
    holder.tvJudul.setText(tanaman.judul);
    /*holder.tvHarga.setText(tanaman.harga);*/
    holder.ivFoto.setImageDrawable(tanaman.foto);
    holder.tvJudul.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
}



@Override
public int getItemCount() {
    if(makananList!=null)
        return makananList.size();
    return 0;
}

public class ViewHolder extends RecyclerView.ViewHolder {
    ImageView ivFoto;
    TextView tvJudul;
    TextView tvHarga;

    public ViewHolder(View itemView) {
        super(itemView);
        ivFoto = (ImageView) itemView.findViewById(R.id.imageView);
        tvJudul = (TextView) itemView.findViewById(R.id.textViewJudul);
        /*tvHarga = (TextView) itemView.findViewById(R.id.textViewHarga);*/
    }
}}

如何在AdapterClass中使用RecyclerView?

1 个答案:

答案 0 :(得分:1)

使你的构造函数像这样

private Context context;
public MakananAdapter(ArrayList<Makanan> makananList, Context context) {
    this.makananList = makananList;
    this.context = context;
}

初始化适配器时传递context

MakananAdapter = new MakananAdapter(makananList, this);

onClickListner中的适配器中,这样做

holder.tvJudul.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {

        Intent openNextActivity = new Intent(context, yourActivityName.class);
        context.startActivity(openNextActivity)
     }
});