包含ListView的Android片段



试图获得一个包含片段内数据的列表视图。我知道我的代码应该可以工作,但它没有。Als尝试使用ListFragment代替Fragment,使用BaseAdapter代替ArrayAdapter,但两者都不起作用。

碎片

public class ContactsFragment extends Fragment {
  private DashboardActivity dashboard;
  private List<User> contacts;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
    ...
    ...
    ListView contactsListView = (ListView)rootView.findViewById(R.id.contacts_list_view);
    ContactsListAdapter contactsListAdapter = new ContactsListAdapter(getActivity(), contacts);
    contactsListView.setAdapter(contactsListAdapter);
    return rootView;
}

适配器

public class ContactsListAdapter extends ArrayAdapter<User> {
  private Context context;
  private List<User> contacts;
  public ContactsListAdapter(Context context, List<User> contacts) {
      super(context, R.layout.contact_list_item);
      this.context = context;
      this.contacts = contacts;
  }
  @Override
  public View getView(int position, View convertView, ViewGroup viewGroup) {
    User contact = contacts.get(position);
    View contactView = convertView;
    if (contactView == null) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        contactView = inflater.inflate(R.layout.contact_list_item, null);
    }
    TextView contactEmail = (TextView)contactView.findViewById(R.id.contact_item_email);
    contactEmail.setText(contact.getEmail());
    TextView contactPhone = (TextView)contactView.findViewById(R.id.contact_item_phone);
    contactPhone.setText(contact.getPhone());
    return contactView;
}

我错过什么了吗?也许使用其他基类?

试试这个:

public ContactsListAdapter(Context context, List<User> contacts) {
   super(context, R.layout.contact_list_item,contacts); //change here
   this.context = context;
   this.contacts = contacts;
}

最新更新