我正在使用RecyclerView
& CardView
小部件显示用户添加的联系人。
我创建了用户界面,但我不知道如何使用RecyclerView
进行上述操作。怎么解决这个问题?
答案 0 :(得分:2)
要将联系人绑定到CardView
,您需要创建ArrayList<>
来存储联系人以便绑定它们。首先,创建一个名为Contact.java
的新类,并添加以下代码:
public class Contact {
public String name;
public int number;
public Contact(String name, int number) {
this.name = name;
this.number = number;
}
}
此课程将确保ArrayList<>
中的每个实例都具有联系人姓名和电话号码所需的值。现在,我们需要创建一个适配器类来管理CardView
中的点击事件,并将ArrayList<>
中的值绑定到View
内的CardView
。创建一个名为ContactsAdapter.java
的新类,并添加以下代码:
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ContactsViewHolder> {
public List<Contact> list;
public ContactsAdapter(List<ContactsAdapter> list) {
this.list = list;
}
public static class ContactsViewHolder extends RecyclerView.ViewHolder {
// Update:
RelativeLayout item;
ImageView photo;
TextView name;
TextView number;
public ContactsViewHolder(View view) {
super(view);
// Update:
item = (RelativeLayout) view.findViewById(R.id.id_to_rel_layout); // If not, then add one by using android.id="@+id/whatever"
photo = (ImageView) view.findViewById(R.id.contact_photo);
name = (TextView) view.findViewById(R.id.contact_name);
number = (TextView) view.findViewById(R.id.contact_number);
}
}
@Override
public ContactsViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.contacts_layout, viewGroup, false);
ContactsViewHolder viewHolder = new ContactsViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ContactsViewHolder viewHolder, final int position) {
// Update:
item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Do onclick stuff here such as dialing someone
}
});
viewHolder.photo.setImageURI(your_uri);
viewHolder.name.setText(list.get(position).name);
viewHolder.number.setText(list.get(position).number);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public int getItemCount() {
return list.size();
}
}
现在我们必须将适配器附加到RecyclerView
。在包含相应RecyclerView
的活动中,添加以下代码:
private List<Contact> list = new ArrayList<>;
public void loadContacts() {
list.add(new Contacts(photoUri, name, number));
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.your_recyclerview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
ContactsAdapter adapter = new ContactsAdapter(list);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
您已成功将联系人与CardView
绑定。告诉我你怎么走。