Learning Android gridview
1: simple original gridview layout: http://blog.csdn.net/jiabinjlu/article/details/6921008
In this example, simpleadapter is used to connect the data source and the gridview.
2: By Rewriting the adapter, make some changes to the layout of the gridview: http://jackxlee.blog.51cto.com/2493058/674409
In this example, a custom adapter is used to connect the data source and the gridview.
Package com. example. gridviewdemo;
Import Android. content. context;
Import Android. View. layoutinflater;
Import Android. View. view;
Import Android. View. viewgroup;
Import Android. widget. baseadapter;
Import Android. widget. imageview;
Import Android. widget. textview;
Public class imageadapter extends baseadapter {
Private context;
Public imageadapter (context ){
This. Context = context;
}
Private integer [] images = {
R. drawable. get1,
R. drawable. get2,
R. drawable. get3,
R. drawable. get4,
R. drawable. get5,
R. drawable. get6
};
Private string [] texts = {
"Music ",
"Sky ",
"Document ",
"Chip ",
"Audio ",
"Audio"
};
@ Override
Public int getcount (){
// Todo auto-generated method stub
Return images. length;
}
@ Override
Public object getitem (INT position ){
// Todo auto-generated method stub
Return position;
}
@ Override
Public long getitemid (INT position ){
// Todo auto-generated method stub
Return position;
}
@ Override
Public View getview (INT position, view convertview, viewgroup parent ){
// Todo auto-generated method stub
Imgtextwrapper wrapper;
If (convertview = NULL ){
Wrapper = new imgtextwrapper ();
Layoutinflater Inflater = layoutinflater. From (context );
// Obtain the layout format of each item
Convertview = Inflater. Inflate (R. layout. gridview_item, null );
// Set an object
Convertview. settag (wrapper );
// Set the margin
Convertview. setpadding (15, 15, 15, 15 );
} Else {
Wrapper = (imgtextwrapper) convertview. gettag ();
}
Wrapper. imageview = (imageview) convertview. findviewbyid (R. Id. imageview_item );
// Set the corresponding image as its background on the corresponding bitmap
Wrapper. imageview. setbackgroundresource (images [position]);
Wrapper. textview = (textview) convertview. findviewbyid (R. Id. textview_item );
Wrapper. textview. settext (texts [position]);
Return convertview;
}
// This class encapsulates pictures and text
Class imgtextwrapper {
Imageview;
Textview;
}
}
Then in the main program:
// Find the container
Gridview = (gridview) findviewbyid (R. Id. gridview1 );
// Imageadapter is a custom adapter,
Imageadapter adapter = new imageadapter (this );
// Connect the data source and container through the adapter
Gridview. setadapter (adapter );