我正在处理Android应用程序代码,并且扩展了ArrayAdapter
类,但收到此错误消息Item cannot be cast to com.example.sharingapp.Contact
下面是我的代码:
package com.example.sharingapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ContactAdapter extends ArrayAdapter<Contact> {
private LayoutInflater inflater;
private Context context;
public ContactAdapter(Context context, ArrayList<Contact> contacts) {
super(context, 0, contacts);
this.context = context;
this.inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// getItem(position) gets the "contact" at "position" in the "contacts" ArrayList
// (where "contacts" is a parameter in the ContactAdapter creator as seen above ^^)
Contact contact = getItem(position);
String username = "Username: " + contact.getUsername();
String email = "Email: " + contact.getEmail();
// Check if an existing view is being reused, otherwise inflate the view.
if (convertView == null) {
convertView = inflater.from(context).inflate(R.layout.contactlist_contact, parent, false);
}
TextView username_tv = (TextView) convertView.findViewById(R.id.username_tv);
TextView email_tv = (TextView) convertView.findViewById(R.id.email_tv);
ImageView photo = (ImageView) convertView.findViewById(R.id.contacts_image_view);
photo.setImageResource(android.R.drawable.ic_menu_gallery);
username_tv.setText(username);
email_tv.setText(email);
return convertView;
}
}
错误涉及以下行:Contact contact = getItem(position);
2条答案
按热度按时间x7rlezfr1#
您需要在适配器中保留一个“联系人”列表。
你需要这样的东西:
然后,在构造函数上:
然后重写“getItem”以从您的“contactList”返回具有给定位置的联系人:
dced5bon2#
这是Coursera课程面向对象设计的代码库。
我遇到了类似的问题,我通过修复ContactList类loadContacts方法中的代码解决了这个问题,从ItemList类复制此方法后,需要设置正确的ArrayList类型。