分类:C#、Android、VS2015;
创建日期:2016-02-07
一、简介图库(也叫画廊)是一个布局小部件,用于在可水平滚动的列表中显示每一副图片,当前所选的图片将置于视图的中心。
注意:Android已经弃用了这个小部件,弃用的原因是用Galery实现的效率比较低,官方的建议是改为用HorizontalScrollView来替代这个小部件。但是,目前手机上的图片浏览功能很多都是用Galery来实现的,如果你仍然喜欢这个小部件,也可以在高版本的项目中继续使用它。
二、示例8--Demo08Gallery1、运行截图
在模拟器中用鼠标左右拖放图片观察效果。
[flash=500,400]http://s1.knowsky.com/20160211/wgn3r2hmpvw52.png[/flash]
2、添加Demo08Gallery.axml文件
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns: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"><Galleryandroid:id="@+id/gallery"android:layout_width="fill_parent"android:layout_height="wrap_content"/></LinearLayout>
保存文件,然后单击解决方案资源管理器上方的【刷新】按钮。
3、添加Demo08Gallery.cs文件
usingSystem;usingAndroid.App;usingAndroid.Content;usingAndroid.OS;usingAndroid.Views;usingAndroid.Widget;usingjava.Lang;namespacech05demos.SrcActivity
{
[Activity(Label="Demo08Gallery")]publicclassDemo08Gallery : Activity
{PRotectedoverridevoidOnCreate(Bundle savedInstanceState)
{base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.demo08_Gallery);varg = FindViewById<Gallery>(Resource.Id.gallery);
g.Adapter=newImageAdapter(this)
{
CurrentWidth=550,
CurrentHeight=550};
g.ItemClick+=Gallery_ItemClick;
}privatevoidGallery_ItemClick(objectsender, AdapterView.ItemClickEventArgs e)
{
Toast.MakeText(this, e.Position.ToString(), ToastLength.Short).Show();
}
}publicclassImageAdapter : BaseAdapter
{privateContext context;privateint[] 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可以这样用)publicintCurrentWidth {get;set; } =500;publicintCurrentHeight {get;set; } =500;publicImageAdapter(Context c)
{
context=c;
}publicoverrideintCount
{get{returnthumbIds.Length; }
}publicoverrideView GetView(intposition, View convertView, ViewGroup parent)
{
ImageView i=newImageView(context);
i.SetImageResource(thumbIds[position]);
i.LayoutParameters=newGallery.LayoutParams(500,500);
i.SetScaleType(ImageView.ScaleType.FitXy);returni;
}publicoverridelongGetItemId(intposition)
{return0;
}publicoverrideJava.Lang.Object GetItem(intposition)
{returnnull;
}
}
}
运行。