首页 > 代码库 > xamarin android——数据绑定到控件(二)

xamarin android——数据绑定到控件(二)

本示例为通过媒体内容提供器获取本机中的图片显示在Gallery中。

活动中简单的初始化代码

private void InitGallery()
        {
            Gallery gallery = FindViewById<Gallery> (Resource.Id.gallery);
            gallery.Adapter = new ImageAdapter (this);
        }
ImageAdapter 类为自己定义的适配器,继承BaseAdapter类,其中核心代码为GetView方法。
BaseAdapter为抽象类必须实现指定方法,右键BaseAdapter类,选择Implement Abstract Class,添加要实现的方法。

ImageAdapter 的代码实现
public class ImageAdapter:BaseAdapter
    {
        private Context context;

        public ImageAdapter(Context context)
        {
            this.context = context;
        }

        #region implemented abstract members of BaseAdapter
        public override Java.Lang.Object GetItem (int position)
        {
            ImageCursor.MoveToPosition (position);
            return ImageCursor.GetString (0);
        }
        public override long GetItemId (int position)
        {
            return position;
        }
        public override View GetView (int position, View convertView, ViewGroup parent)
        {
       //避免不断的销毁和创建新视图
if (convertView == null) { ImageView imageView = new ImageView (context); ImageCursor.MoveToPosition (position); var imageUrl = ImageCursor.GetString (0); Console.WriteLine (imageUrl);
       //根据输出判断 MediaStore.Images.Media.InterfaceConst.Data 查询结果为图片路径
//imageView.SetImageURI (Android.Net.Uri.WithAppendedPath(MediaStore.Images.Media.ExternalContentUri,imageID)); imageView.SetImageURI (Android.Net.Uri.Parse(imageUrl)); imageView.SetScaleType (ImageView.ScaleType.FitCenter); return imageView; } else { return convertView as ImageView; } } public override int Count { get { return ImageCursor.Count; } } #endregion private Android.Database.ICursor imageCursor; public Android.Database.ICursor ImageCursor { get{ if (imageCursor==null) { imageCursor = GetImageCursor (); } return imageCursor; } set{ imageCursor = value; } } //查询本机图片 private Android.Database.ICursor GetImageCursor(){ return (context as Activity).ManagedQuery (MediaStore.Images.Media.ExternalContentUri, new string[] {MediaStore.Images.Media.InterfaceConsts.Data},null,null,null); } }

注意:一定要保证本机或者模拟器中存在图片文件,不然会报出No entry for content的异常。

此外学的过程中了解到一个Xamarin组件,地址:http://components.xamarin.com/view/xamarin.mobile,不知道效果怎么要。