The following code is copied directly to the project and can be run using. As we all know, the nine Gongge of Android can be implemented with the GridView control, which first defines a
Gridview.xml
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" > <GridViewAndroid:id= "@+id/gv_home"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:numcolumns= "3" > </GridView></LinearLayout>
And then you have to define a gridview_item.xml.
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:gravity= "Center"android:orientation= "vertical" > <ImageViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:id= "@+id/iv_icon"android:src= "@drawable/ic_launcher" /> <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:id= "@+id/tv_title"Android:text= "Module title"android:textsize= "18SP" /></LinearLayout>
Now that the layout is implemented, the next step is the Android code. It is important to note that the GridView adapter cannot be missing.
Public classMainactivityextendsActivity {PrivateGridView Gv_home; Privatestring[] Mtitlestrs; Private int[] mdrawableids; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_home); Initui (); //methods for initializing dataInitData (); } Private voidInitData () {mtitlestrs=Newstring[]{"1", "2", "3", "4", "5", "6", "7", "8", "9"};//Note that the numbers here should correspond to the following image ID one by one, otherwise the effect will not match the text imageMdrawableids =New int[]{r.drawable.ic_launcher,r.drawable.ic_launcher, r.drawable.ic_launcher,r.drawable . Ic_launcher, R.drawable.ic_launcher,r.drawable.ic_launcher, R.drawable.ic_launcher,r.drawable.ic_launcher,r.drawable.ic_launcher}; //Nine Gongge control set data adapter (equivalent to a ListView data adapter)Gv_home.setadapter (NewMyadapter ()); } classMyadapterextendsbaseadapter{@Override Public intGetCount () {returnmtitlestrs.length; } @Override PublicObject GetItem (intposition) { returnMtitlestrs[position]; } @Override Public LongGetitemid (intposition) { returnposition; } @Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {View View= View.inflate (Getapplicationcontext (), R.layout.gridview_item,NULL); ImageView Iv_icon=(ImageView) View.findviewbyid (R.id.iv_icon); TextView Tv_title=(TextView) View.findviewbyid (r.id.tv_title); Tv_title.settext (Mtitlestrs[position]); Iv_icon.setbackgroundresource (Mdrawableids[position]); returnview; } } Private voidInitui () {gv_home=(GridView) Findviewbyid (r.id.gv_home); }}
Android Nine Gongge