我正在使用 RecyclerView 来绑定适配器中的对象列表。
使用 SetOnItemClickListener 我可以拦截RecycleView元素的点击,但是我需要访问绑定对象的属性(例如:字段名称)以便在发送到其他活动时单击按钮。
这怎么可能?
答案 0 :(得分:2)
我认为你正在混合使用ListView和RecylerView的想法。 RecylerView面向ViewHolder,因此您应该在ViewHolder上处理click事件。这很简单。
public class ObjectClass {
public String property1;
public String property2;
...
}
public class ObjectAdapter extends RecyclerView.Adapter<ObjectViewHolder> {
private Context mContext;
private List<ObjectClass> mObjects;
public ObjectAdapter(Context context) {
mContext = context;
}
public ObjectClass getItem(int position) {
return mObjects != null ? mObjects.get(position) : null;
}
@Override
public int getItemCount() {
return mObjects != null ? mObjects.size() : 0;
}
@Override
public ObjectViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ObjectViewHolder(LayoutInflater.from(mContext)
.inflate(R.layout.item_layout, parent, false));
}
@Override
public void onBindViewHolder(ObjectViewHolder holder, int position) {
// bind the item with ViewHolder here
holder.item = getItem(position);
}
public static class ObjectViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
private ObjectClass item;
public ObjectViewHolder(View view) {
super(view);
view.setOnClickListener(this);
}
public void onClick(View v) {
// do stuff with item's properties...
}
}
}
答案 1 :(得分:0)
package com.example.gmehdibalti.jasonpracticwthree;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by G Mehdi Balti on 5/16/2016.
*/
public class myAdapter extends RecyclerView.Adapter<myAdapter.ContactViewHolder>{
ArrayList<UserModel> list;
Activity activity;
public myAdapter(ArrayList<UserModel> list, Activity activity) {
this.list = list;
this.activity = activity;
}
@Override
public myAdapter.ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell, parent, false);
ContactViewHolder cvh=new ContactViewHolder(v);
return cvh;
}
@Override
public void onBindViewHolder(myAdapter.ContactViewHolder holder, int position) {
ContactViewHolder cvh=holder;
UserModel abc=list.get(position);
cvh.txt_id.setText(abc.getId());
cvh.txt_name.setText(abc.getName());
cvh.txt_email.setText(abc.getEmail());
}
@Override
public int getItemCount() {
return list.size();
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
TextView txt_name;
TextView txt_id;
TextView txt_email;
public ContactViewHolder(View itemView) {
super(itemView);
txt_id = (TextView)itemView.findViewById(R.id.txt_Id_item);
txt_name = (TextView)itemView.findViewById(R.id.txt_name_item);
txt_email = (TextView)itemView.findViewById(R.id.txt_email_item);
}
}
}