(This article is based on the official tutorials translation)
Preface
Using Official case studies is the most direct method. This section describes the application of gallery in combination with books.
Effect
Classes involved
· Baseadapter
· Gallery
· Imageview
· Adapterview. onitemclicklistener
The following is the structure of the project,
New: 1) a main activity is named hellogalleryactivity. java,
2) a custom adapter named galleryadapter is used to fill the gallery
3) place used image resources in drawable
4) Create an XML file in values. atrrs. XML is used to define the border effect of the image.
5) Add a gallery in Mian. xml.
Code writing:
Add the following code to the oncreate () method rewritten in hellogalleryactivity:
Public void oncreate (bundle savedinstancestate)
{
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Gallery gallery = (Gallery) findviewbyid (R. Id. gallery1 );
Gallery. setadapter (New galleryadapter (this ));
// The following click listener is used to display a toast, which is used to display the subscript of the clicked Image
Gallery. setonitemclicklistener (New onitemclicklistener ()
{
@ Override
Public void onitemclick (adapterview parent, view V, int position, long ID)
{
Toast. maketext (hellogalleryactivity. This, "" + position, Toast. length_short). Show ();
}
});
}
In the galleryadapter, some methods to be rewritten are automatically generated:
Public class galleryadapter extends baseadapter
{
// Used for the background border of the image
Int mgalleryitembackground;
// Obtain Context Reference
Private context mcontext;
// An integer array for storing image resources
Private integer [] mimageids = {
R.drawable.sample_1,
R.drawable.sample_2,
R.drawable.sample_3,
R.drawable.sample_4,
R.drawable.sample_5,
R.drawable.sample_6,
R. drawable. sample_7 };
// Rewrite the constructor,
Public galleryadapter (context c)
{
Mcontext = C;
// Set the border Style
Typedarray A = C. obtainstyledattributes (R. styleable. hellogallery );
Mgalleryitembackground = A. getresourceid (
R. styleable. hellogallery_android_galleryitembackground, 0 );
A. Recycle ();
}
@ Override
Public int getcount ()
{
Return mimageids. length;
}
@ Override
Public object getitem (INT position)
{
Return position;
}
@ Override
Public long getitemid (INT position)
{
Return position;
}
@ Override
Public View getview (INT position, view convertview, viewgroup parent)
{
Imageview I = new imageview (mcontext );
I. setimageresource (mimageids [position]);
I. setlayoutparams (new gallery. layoutparams (150,100 ));
I. setscaletype (imageview. scaletype. fit_xy );
I. setbackgroundresource (mgalleryitembackground );
Return I;
}
}
Improve the atrrs. xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="HelloGallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
Basically, this is OK.
Source code download