xamarin android——資料繫結到控制項(二)

來源:互聯網
上載者:User

標籤:android   style   class   blog   c   code   

本樣本為通過媒體內容提供器擷取本機中的圖片顯示在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,不知道效果怎麼要。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.