[monoandroid在列表视图中读取联系人和电话号码

问题描述 投票:0回答:1

我想要一种显示姓名,电话号码和图像并将其显示在listView中的方法。

我尝试了以下代码来提取名称,但它不起作用。


     var uri = ContactsContract.Contacts.ContentUri;  
        string[] projection = {  
            ContactsContract.Contacts.InterfaceConsts.Id,  
            ContactsContract.Contacts.InterfaceConsts.DisplayName

        };  
        var cursor = ManagedQuery(uri, projection, null, null, null);  
        var contactList = new List < string > ();  
        if (cursor.MoveToFirst()) {  
            do {  
                contactList.Add(cursor.GetString(cursor.GetColumnIndex(projection[1])));  
            } while (cursor.MoveToNext());  
        }
            ListView.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, contactList);
xamarin.android
1个回答
0
投票

我做一个样本,您可以看一下:

布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:id="@+id/ContactsListView" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" />
  </LinearLayout>

ListView项目用户界面:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">
<ImageView 
    android:id="@+id/ContactImage" 
    android:layout_width="50dp" 
    android:layout_height="50dp" 
    android:layout_margin="5dp" />
<LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" 
 android:orientation="vertical"  
 android:layout_marginLeft="5dp">
<TextView
    android:id="@+id/ContactName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    />

  <TextView android:id="@+id/ContactNumber"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>
</LinearLayout>

</LinearLayout>

联系人类别:

 public class Contact
{
    public long Id { get; set; }
    public string DisplayName { get; set; }
    public string PhoneNumber { get; set; }
    public string PhotoId { get; set; }
}

显示光标数据的自定义适配器:

 public class ContactsAdapter : BaseAdapter
{
    List<Contact> contactList;
    Activity activity;

    public ContactsAdapter(Activity activity)
    {
        this.activity = activity;

        FillContacts();
    }

    public override int Count
    {
        get { return contactList.Count; }
    }

    public override Java.Lang.Object GetItem(int position)
    {
        return null; // could wrap a Contact in a Java.Lang.Object to return it here if needed
    }

    public override long GetItemId(int position)
    {
        return contactList[position].Id;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var view = convertView ?? activity.LayoutInflater.Inflate(Resource.Layout.ContactListItem, parent, false);
        var contactName = view.FindViewById<TextView>(Resource.Id.ContactName);
        var contactImage = view.FindViewById<ImageView>(Resource.Id.ContactImage);
        var contactNumber = view.FindViewById<TextView>(Resource.Id.ContactNumber);

        contactName.Text = contactList[position].DisplayName;
        contactNumber.Text = contactList[position].PhoneNumber;

        if (contactList[position].PhotoId == null)
        {

            contactImage = view.FindViewById<ImageView>(Resource.Id.ContactImage);
            contactImage.SetImageResource(Resource.Drawable.ContactImage);

        }
        else
        {

            var contactUri = ContentUris.WithAppendedId(ContactsContract.Contacts.ContentUri, contactList[position].Id);
            var contactPhotoUri = Android.Net.Uri.WithAppendedPath(contactUri, Contacts.Photos.ContentDirectory);

            contactImage.SetImageURI(contactPhotoUri);
        }
        return view;
    }

    void FillContacts()
    {
        //var uri = ContactsContract.Contacts.ContentUri;

        var uri = ContactsContract.CommonDataKinds.Phone.ContentUri;

        string[] projection = {
            ContactsContract.Contacts.InterfaceConsts.Id,
            ContactsContract.Contacts.InterfaceConsts.DisplayName,
             ContactsContract.CommonDataKinds.Phone.Number,
           ContactsContract.Contacts.InterfaceConsts.PhotoId
           //ContactsContract.Contacts.InterfaceConsts.PhotoThumbnailUri
        };

        // ManagedQuery is deprecated in Honeycomb (3.0, API11)
        //var cursor = activity.ManagedQuery (uri, projection, null, null, null);

        // ContentResolver requires you to close the query yourself
        //var cursor = activity.ContentResolver.Query(uri, projection, null, null, null);

        // CursorLoader introduced in Honeycomb (3.0, API11)
        var loader = new CursorLoader(activity, uri, projection, null, null, null);
        var cursor = (ICursor)loader.LoadInBackground();


        contactList = new List<Contact>();

        if (cursor.MoveToFirst())
        {
            do
            {
                contactList.Add(new Contact
                {
                    Id = cursor.GetLong(cursor.GetColumnIndex(projection[0])),
                    DisplayName = cursor.GetString(cursor.GetColumnIndex(projection[1])),
                    PhoneNumber = cursor.GetString(cursor.GetColumnIndex(projection[2])),
                    PhotoId = cursor.GetString(cursor.GetColumnIndex(projection[3]))
                });
            } while (cursor.MoveToNext());
        }
    }
}

MainActivity:

 public class MainActivity : AppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.layout4);

        if (ActivityCompat.CheckSelfPermission(this, Android.Manifest.Permission.ReadContacts) != Android.Content.PM.Permission.Granted)
        {

            ActivityCompat.RequestPermissions(this, new string[] { Android.Manifest.Permission.ReadContacts }, 1);

        }

        var contactsAdapter = new ContactsAdapter(this);
        var contactsListView = FindViewById<ListView>(Resource.Id.ContactsListView);
        contactsListView.Adapter = contactsAdapter;
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

请不要忘记请求联系人权限。

这是Github上的示例,您可以看一下:

https://github.com/CherryBu/ContactApp

[更多详细信息,您可以看一下这篇文章:

https://docs.microsoft.com/en-us/xamarin/android/platform/content-providers/contacts-contentprovider#displaying-the-cursor-data-with-a-custom-adapter

更新:

在ContactsAdapter中设置静态列表,

public static List<Contact> contactList;

然后在OnCreate方法中调用ListView.ItemClick事件。

contactsListView.ItemClick += ContactsListView_ItemClick;

   private void ContactsListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
    {
        string selectnumber = ContactsAdapter.contactList[e.Position].PhoneNumber;
        var toast = Toast.MakeText(this, selectnumber, Android.Widget.ToastLength.Short);
        toast.Show();
    }

截图:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.