九宫格

 一、XML代码

1、Activity代码部分
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.administrator.jiugongge.MainActivity"> <GridView android:id="@+id/grid" android:layout_width="match_parent" android:layout_height="match_parent" android:columnWidth="90dp" android:gravity="center" android:horizontalSpacing="10dp" android:verticalSpacing="10dp" android:numColumns="3"/> RelativeLayout>

 

2、新建LayoutXML代码
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal"> <LinearLayout android:layout_width="80dp" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/e"/> <TextView android:id="@+id/txt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textColor="#000000" android:textSize="15dp" android:gravity="center"/> LinearLayout> RelativeLayout>

二、JAVA代码及功能实现

package com.example.administrator.jiugongge;
public class MainActivity extends AppCompatActivity { private int[] photo = { R.mipmap.a, R.mipmap.b, R.mipmap.c, R.mipmap.d, R.mipmap.e, R.mipmap.f, R.mipmap.g, R.mipmap.h, R.mipmap.p, }; private String[] name = { "a", "b", "c", "d", "e", "f", "g", "h", "p" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GridView grid = (GridView) findViewById(R.id.grid); int length = photo.length;  ArrayList> lstImage = new ArrayList>(); for (int i = 0; i < length; i++) { HashMap map = new HashMap(); map.put("Image", photo[i]); map.put("Text", name[i]); lstImage.add(map); } SimpleAdapter wangqi = new SimpleAdapter(this, lstImage, R.layout.layout, new String[]{"Image", "Text"}, new int[]{R.id.img, R.id.txt});  grid.setAdapter(adapter); } }

你可能感兴趣的:(九宫格)