我有一个listview,我使用自定义适配器。每个列表项都有三个textview。
我的要求是,我必须从第一个列表项中获取文本。
我尝试了以下代码,但没有工作
ListView listView = (ListView) findViewById(R.id.contactList);
listView.setAdapter(new CustomAdapter(ContactListActivity.this, contactList));
Contact contact = (Contact)listView.getItemAtPosition(0);
String firstName = contact.getDisplayName();
contactList是自定义对象Contact的arraylist,它有3个字段名称,phone&电子邮件。
我的适配器代码
类CustomAdapter扩展BaseAdapter { 私人名单contactList; private LayoutInflater inflater;
public CustomAdapter(Context context, List<Contact> contactList2) {
inflater = LayoutInflater.from(context);
this.contactList = contactList2;
}
@Override
public int getCount() {
return contactList.size();
}
@Override
public Object getItem(int position) {
return contactList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.contactlistitem, null);
holder = new viewHolder();
holder.name = (TextView) convertView.findViewById(R.id.txtDisplayName);
holder.number = (TextView) convertView.findViewById(R.id.txtPhone);
holder.email = (TextView) convertView.findViewById(R.id.txtMailID);
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
}
holder.name.setText(contactList.get(position).getDisplayName());
holder.number.setText(contactList.get(position).getPhone());
holder.email.setText(contactList.get(position).getEmail());
return convertView;
}
public class viewHolder {
TextView name;
TextView number;
TextView email;
}
}
我的错误是什么,有什么建议吗?
答案 0 :(得分:1)
试试这个
Contact contact = (Contact) listView.getAdapter().getItem(position);
String firstName = contact.getDisplayName();
答案 1 :(得分:1)
为什么你需要从ListView
或Adapter
获取第一项。你已经有ArrayList
数据就这样了......
Contact contact = contactList.get(0);
String firstName = contact.getDisplayName();
基于OP要求 像这样改变..
CustomAdapter adapter = new CustomAdapter(ContactListActivity.this, contactList);
listView.setAdapter(adapter);
Contact contact = (Contact)adapter.getItem(0);
String firstName = contact.getDisplayName();