GridView
- PDF for offline use
Let us know how you feel about this
Translation Quality
0/250
last updated: 2017-08
GridView is a
ViewGroup
that displays items in a two-dimensional, scrollable grid. The grid
items are automatically inserted to the layout using a
ListAdapter.
In this tutorial, you'll create a grid of image thumbnails. When an item is selected, a toast message will display the position of the image.
Start a new project named HelloGridView.
Find some photos you'd like to use, or download these sample images. Add the image files to the project's Resources/Drawable directory. In the Properties window, set the Build Action for each to AndroidResource.
Open the Resources/Layout/Main.axml file and insert the following:
<?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" />This
GridViewwill fill the entire screen. The attributes are rather self explanatory. For more information about valid attributes, see theGridViewreference.Open
HelloGridView.csand insert the following code for theOnCreate()method:protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); SetContentView (Resource.Layout.Main); var gridview = FindViewById<GridView> (Resource.Id.gridview); gridview.Adapter = new ImageAdapter (this); gridview.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) { Toast.MakeText (this, args.Position.ToString (), ToastLength.Short).Show (); }; }After the Main.axml layout is set for the content view, the
GridViewis captured from the layout withFindViewById. TheAdapterproperty is then used to set a custom adapter (ImageAdapter) as the source for all items to be displayed in the grid. TheImageAdapteris created in the next step.To do something when an item in the grid is clicked, an anonymous delegate is subscribed to the
ItemClickevent. It shows aToastthat displays the index position (zero-based) of the selected item (in a real world scenario, the position could be used to get the full sized image for some other task). Note that Java-style listener classes can be used instead of .NET events.Create a new class called
ImageAdapterthat subclassesBaseAdapter:public class ImageAdapter : BaseAdapter { Context context; public ImageAdapter (Context c) { context = c; } public override int Count { get { return thumbIds.Length; } } public override Java.Lang.Object GetItem (int position) { return null; } public override long GetItemId (int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public override View GetView (int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView (context); imageView.LayoutParameters = new GridView.LayoutParams (85, 85); imageView.SetScaleType (ImageView.ScaleType.CenterCrop); imageView.SetPadding (8, 8, 8, 8); } else { imageView = (ImageView)convertView; } imageView.SetImageResource (thumbIds[position]); return imageView; } // references to our images int[] thumbIds = { Resource.Drawable.sample_2, Resource.Drawable.sample_3, Resource.Drawable.sample_4, Resource.Drawable.sample_5, Resource.Drawable.sample_6, Resource.Drawable.sample_7, Resource.Drawable.sample_0, 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, Resource.Drawable.sample_0, 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 }; }First, this implements some required methods inherited from
BaseAdapter. The constructor and theCountproperty are self-explanatory. Normally,GetItem(int)should return the actual object at the specified position in the adapter, but it's ignored for this example. Likewise,GetItemId(int)should return the row id of the item, but it's not needed here.The first method necessary is
GetView(). This method creates a newViewfor each image added to theImageAdapter. When this is called, aViewis passed in, which is normally a recycled object (at least after this has been called once), so there's a check to see if the object is null. If it is null, anImageViewis instantiated and configured with desired properties for the image presentation:LayoutParamssets the height and width for the View—this ensures that, no matter the size of the drawable, each image is resized and cropped to fit in these dimensions, as appropriate.SetScaleType()declares that images should be cropped toward the center (if necessary).SetPadding(int, int, int, int)defines the padding for all sides. (Note that, if the images have different aspect-ratios, then less padding will cause for more cropping of the image if it does not match the dimensions given to the ImageView.)
If the
Viewpassed toGetView()is not null, then the localImageViewis initialized with the recycledViewobject.At the end of the
GetView()) method, thepositioninteger passed into the method is used to select an image from thethumbIdsarray, which is set as the image resource for theImageView.All that's left is to define the
thumbIdsarray of drawable resources.Run the application.
Your grid layout should look something like this:
Try experimenting with the behaviors of the
GridView and
ImageView
elements by adjusting their properties. For example, instead of using
LayoutParams
try using
SetAdjustViewBounds().
References
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Let us know how you feel about this
Translation Quality
0/250
Xamarin Workbook
If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.


