标签:
分类:C#、Android、VS2015;
创建日期:2016-02-07
图库(也叫画廊)是一个布局小部件,用于在可水平滚动的列表中显示每一副图片,当前所选的图片将置于视图的中心。
注意:Android已经弃用了这个小部件,弃用的原因是用Galery实现的效率比较低,官方的建议是改为用HorizontalScrollView来替代这个小部件。但是,目前手机上的图片浏览功能很多都是用Galery来实现的,如果你仍然喜欢这个小部件,也可以在高版本的项目中继续使用它。
1、运行截图
在模拟器中用鼠标左右拖放图片观察效果。
2、添加Demo08Gallery.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:gravity="center_vertical"> <Gallery android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
保存文件,然后单击解决方案资源管理器上方的【刷新】按钮。
3、添加Demo08Gallery.cs文件
using System; using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Widget; using Java.Lang; namespace ch05demos.SrcActivity { [Activity(Label = "Demo08ActionBar")] public class Demo08Gallery : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.demo08_Gallery); var g = FindViewById<Gallery>(Resource.Id.gallery); g.Adapter = new ImageAdapter(this) { CurrentWidth = 550, CurrentHeight = 550 }; g.ItemClick += Gallery_ItemClick; } private void Gallery_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { Toast.MakeText(this, e.Position.ToString(), ToastLength.Short).Show(); } } public class ImageAdapter : BaseAdapter { private Context context; private int[] thumbIds = { Resource.Drawable.sample_1, Resource.Drawable.sample_2, Resource.Drawable.sample_3, Resource.Drawable.sample_4, Resource.Drawable.sample_5, Resource.Drawable.sample_6, Resource.Drawable.sample_7 }; //默认值为500(这是C# 6.0新增的功能,仅VS2015可以这样用) public int CurrentWidth { get; set; } = 500; public int CurrentHeight { get; set; } = 500; public ImageAdapter(Context c) { context = c; } public override int Count { get { return thumbIds.Length; } } public override View GetView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(context); i.SetImageResource(thumbIds[position]); i.LayoutParameters = new Gallery.LayoutParams(500, 500); i.SetScaleType(ImageView.ScaleType.FitXy); return i; } public override long GetItemId(int position) { return 0; } public override Java.Lang.Object GetItem(int position) { return null; } } }
运行。
标签:
原文地址:http://www.cnblogs.com/rainmj/p/5184558.html