We will use two examples to learn the gridview. Grid and table are a little similar. In this example, we will gradually describe how to compile a grid activity.
Example 1: Inherit arrayadapter as a custom Adapter
1. Compile Android XML
<? 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">
<Textview Android: Id = "@ + ID/selection4"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"/>
<GridviewAndroid: Id = "@ + ID/grid"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android:Verticalspacing= "35px" <! -- Vertical interval between grid elements -->
Android:Horizontalspacing= "5px"
<! -- Horizontal interval between grid elements -->
Android:Numcolumns= "Auto_fit" <! -- Indicates the number of columns. If it is set to auto_fit, it is automatically calculated based on columnwidth and Spacing -->
Android:Columnwidth= "100px" <! -- Generally, dip or DP with pixel density independence is recommended. -->
Android:Stretchmode= "Columnwidth"
<! -- How to fill the free space? The simulator uses wvga800 * 480, with 4 columns in each row, 4*100 + 5*3 = 415, and a 65px space remaining. If columnwidth is used, the remaining 65 will be allocated to four columns, with each column increasing by 16/17 PX. If spacingwidth is used, three gaps are allocated -->
Android: gravity = "center"/>
</Linearlayout>
2. write the code. As well as other selected widgets, the previously learned listview and spinner methods provide data and sub-View display styles through setonitemselectedlistener (), and select listner by triggering setonitemselectedlistener () registration. In addition to the processing options, we add a click trigger to compare the two differences. This time, we no longer use the built-in Android format, but set our own UI style.
Public class chapter7test4 extends activity implementsOnitemselectedlistener,Onitemclicklistener{
Private textview selection = NULL;
Private string [] items = {"lorem", "ipsum", "dolor", "sit", "Amet", "hello", "me", "elit ", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat ", "placerat", "Ante", "Hi", "sodales", "test", "augue", "Purus "};
@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. chapter_7_test4 );
Selection = (textview) findviewbyid (R. Id. selection4 );
Gridview grid = (gridview) findviewbyid (R. Id. Grid );
//Step 1: Set the arrayadapter. You can use or customize the arrayadapter format that comes with Android. We will define it here.
Grid.Setadapter(NewFunnylookingadapter(This, Android. R. layout. simple_list_item_1, items ));
// Grid. setadapter (New arrayadapter <string> (this, Android. R. layout. simple_list_item_1, items ));
// Step 2: Set the elements to be selected and triggered by the clicked callback.
Grid.Setonitemselectedlistener(This );
Grid.Setonitemclicklistener(This );
}
// Step 3: Compile the callback trigger function
@ Override/* this is the onitemselectedlistener interface */
Public void onitemselected (adapterview <?> Arg0, view arg1, int arg2, long arg3 ){
Selection. settext (items [arg2]);
}
@ Override/* this is the onitemselectedlistener interface */
Public void onnothingselected (adapterview <?> Arg0 ){
Selection. settext ("");
}
@ Override/* this is the onitemclicklistener interface */
Public void onitemclick (adapterview <?> Arg0, view arg1, int arg2, long arg3 ){
Selection. settext ("clicked:" + items [arg2]);
}
// Step 4: Write a custom adapter that inherits the arrayadapter <string>
Private classFunnylookingadapter extends arrayadapter <string>{
Private context;
Private string [] theitems;
// Step 4.1: Write the adapterConstructor
Funnylookingadapter (context, int resource, string [] items ){
Super (context, resource, items );
This. Context = context;
Theitems = items;
}
// Step 4.2:Override getview (),Describes the content and UI format of each unit.
/* If textview is not used, you must use getview () to describe each gridview unit. These units can be button and imageview. Here we use button and textview to test override getview (INT, view, viewgroup) respectively, and return any view we want. */
Public ViewGetview(INT position, view convertview, viewgroup parent ){
Textview label = (textview) convertview;
// We test and find that, except the first convertview, all others are null. Therefore, if there is no view, we need to create
If (convertview = NULL ){
Convertview = new textview (context );
Label = (textview) convertview;
}
Label. settext (Position + ":" + theitems [position]);
Return convertview;
}
} // End of class funnylookingadapter
}
The left figure uses the bold format that comes with Android, that is, the annotated setadapter. Figure 2 shows the source code example of the example. The figure right replaces textview with the getview () in funnylookingadapter with a button, this is an interesting phenomenon. The button is used to detect the click action. In the class, we use setitemclicklistener to set the click action for the item detection in the gridview. These two actions overlap, the click of the button will be monitored first, that is, the custom gridview will not be triggered, which requires special attention.
Example 2:Inherit baseadapter as custom Adapter
This is an example from totorial. Here, the element in the gridview is imageview. The android XML file is simple:
<? XML version = "1.0" encoding = "UTF-8"?>
<! -- DP is equivalent to dip. Device Independent pixels is an independent pixel. It is mostly used for Android and has nothing to do with the separation rate. -->
<GridviewXmlns: 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">
</Gridview>
Let's take a look at Java code.
1) copy the image to RES/drawable-hdpi.
2) set the gridview adapter, set the click trigger function, and use toast to display the number of clicks.
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. chapter_7_test5 );
Gridview = (gridview) findviewbyid (R. Id. gridview );
Gridview.Setadapter(New imageadapter (this ));
Gridview.Setonitemclicklistener(New onitemclicklistener (){
Public void onitemclick (adapterview <?> Parent, view V, int position, long ID ){
Toast. Maketext (this, "" + position, Toast. length_short). Show ();
}
});
}
3) set the sub-imageadapter to inherit the basadapter.
Public classImageadapter extends baseadapter{
Private context = NULL;
// References to our images
Private integer [] mthumbids = {R. drawable. sample_2, R. drawable. sample_3, R. drawable. sample_4, R. drawable. sample_5, R. drawable. sample_6,
... // Here is the ID of the file, not listed in detail };
// Step 1: Constructor
Public imageadapter (context ){
This. Context = context;
}
// Step 2: The baseadapter needs to refactor the four methods getcount (), getitem (), getitemid (INT position), getview ()
// Step 2.1: getcount () indicates how many items are in the data set represented by this adapter.
Public int getcount (){
Return mthumbids. length;
}
// Step 2.2: getitem ()
Position as needed to obtain the objects placed in the gridview. In this example, we do not need to process the objects in it. It can be set to null.
Public object getitem (INT position ){
Return NULL;
}
// Step 2.3: getitemid ()
Get the row ID (get the row ID associated with the specified position in the list), because we do not need to, simply set it to 0
Public long getitemid (INT position ){
Return 0;
}
// Step 2.4: Get the view in the gridview, get a view that displays the data at the specified position in the data set.
Like the first example, the second function passed may be null and must be processed.
Public View getview (intPosition, View
Convertview, ViewgroupParent){
Imageview = NULL;
If (convertview = NULL ){
Imageview = new imageview (context );
// Set the height and width of the view. This ensures that, regardless of the original size of the image, each image will fit the specified size again.
Imageview.Setlayoutparams(New gridview. layoutparams ));
/* Imageview. scaletype. Center, but do not scale
* Imageview. scaletype. center_crop scales the image proportionally and uniformly (to maintain the image size ratio), so that the two dimensions (width and height) of the image are equal to or greater than the corresponding view dimension.
* Imageview. scaletype. center_inside scales the image proportionally and uniformly (to maintain the image size ratio), so that the two dimensions (width and height) of the image are equal to or less than the corresponding view Dimension */
Imageview.Setscaletype(Imageview. scaletype. center_crop );
Imageview. setpadding (8, 8, 8 );
} Else {
Imageview = (imageview) convertview;
}
Imageview.Setimageresource(Mthumbids [position]);
Return imageview;
}
}
We have set several scaletype options. The figure on the left is imageview. scaletype. center_crop. The image is imageview. scaletype. center_inside, and the image on the right is imageview. scaletype. Center.
Related Links: My andriod development articles