- Xamarin 教程
- Xamarin - 主頁
- Xamarin - 安裝
- Xamarin - 第一個應用程式
- Xamarin - 應用程式清單
- Xamarin - Android 資源
- Xamarin - Android 活動生命週期
- Xamarin - 許可權
- Xamarin - 構建應用程式 GUI
- Xamarin - 選單
- Xamarin - 佈局
- Xamarin - Android 小部件
- Xamarin - Android 對話方塊
- Xamarin - 相簿
- Xamarin - Andriod 檢視
- Xamarin - 多屏應用程式
- Xamarin - 部署應用程式
- Xamarin 有用資源
- Xamarin - 快速指南
- Xamarin - 有用資源
- Xamarin - 討論
Xamarin - 相簿
畫廊是一種檢視型別,用於在可水平滾動的列表中顯示專案。然後將所選專案顯示在中心。在此示例中,你將建立一個包含水平可滾動影像的畫廊。單擊影像時,將顯示所選影像的編號。
首先,建立一個新專案併為其命名,例如畫廊應用程式教程。在開始編寫程式碼之前,將 7 張影像貼上到資源/可繪製資料夾中。導航到resources 資料夾下的main.axml,然後線上性佈局標記之間建立一個相簿。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#d3d3d3">
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp" />
</LinearLayout>
建立一個名為ImageAdapter的新類。此類將用於將影像繫結到我們在上面建立的相簿。
第一步是新增一個包含我們在其中儲存欄位的上下文cont的類。
public class ImageAdapter : BaseAdapter {
Context cont;
public ImageAdapter(Context ct) {
cont = ct;
}
}
接下來,我們計算包含我們影像的陣列列表,並返回其大小。
public override int Count {
get {
return imageArraylist.Length;
}
}
在下一步中,我們獲取專案的 position。以下程式碼演示瞭如何執行此操作。
public override Java.Lang.Object GetItem(int position) {
return null;
}
public override long GetItemId(int position) {
return 0;
}
在下一步中,我們為介面卡引用的專案建立一個imageview。
public override View GetView(int position,View convertView, ViewGroup parent) {
ImageView img = new ImageView(cont);
img.SetImageResource(imageArraylist[position]);
img.SetScaleType(ImageView.ScaleType.FitXy);
img.LayoutParameters = new Gallery.LayoutParams(200, 100);
return img;
}
在最後一步中,我們建立對我們在resources.drawable資料夾中新增的影像的引用。為此,我們建立一個數組來儲存影像集合。以下程式碼介紹瞭如何執行此操作。
int[] imageArraylist = {
Resource.Drawable.img1,
Resource.Drawable.img2,
Resource.Drawable.img3,
Resource.Drawable.img4,
Resource.Drawable.img5,
Resource.Drawable.img6,
};
}
接下來,我們轉到mainActivity.cs並在 OnCreate() 方法下插入以下程式碼。
Gallery myGallery = (Gallery)FindViewById<Gallery>(Resource.Id.gallery);
myGallery.Adapter = new ImageAdapter(this);
myGallery.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs args) {
Toast.MakeText(this,
args.Position.ToString(), ToastLength.Short).Show();
}
最後,構建並執行應用程式以檢視輸出。
廣告