Android网格视图GridView的使用

2019-12-10 19:14:43丽君

  了解了上述的GridView常用xml属性之后,我们就可以完成对主界面的xml布局文件编写了。在xml布局文件中,我们使用LinearLayout对整个界面进行垂直布局,然后在该布局中添加一个GridView控件即可。具体的xml布局文件源码如下:

<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
   xmlns:tools="http://www.easck.com/tools"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent" >
   <GridView 
   android:id="@+id/gridView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:numColumns=""
   android:horizontalSpacing="dp"
   android:verticalSpacing="dp">
   </GridView>
  </LinearLayout> 

  在GridView控件中,我们通过android:numColumns="4"指定了网格的列数为4;通过android:horizontalSpacing="10dp"和android:verticalSpacing="10dp"指定了网格之间的水平距离和垂直距离都为10dp。

2.网格元素布局

  如图1所示,在每个网格内,我们都需要显示两项内容:应用软件图标以及应用软件名称。因此,我们还需要对网格内元素进行相应的布局。

  我们可以在项目工程的layout目录下新建一个名为“griditeminfo.xml”的xml布局文件,完成对网格内元素的布局。在该xml布局文件中,我们使用相对布局RelativeLayout对网格内的元素进行排列,将一个ImageView控件以水平居中的形式放置在网格内(上方),用来显示应用程序的图标;将一个TextView控件以水平居中的形式放置在网格内(下方),用来显示应用程序的名称。具体的griditeminfo.xml源码如下:

<?xml version="." encoding="utf-"?>
  <RelativeLayout xmlns:android="http://www.easck.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" >  
   <ImageView
   android:id="@+id/itemImage"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true" >
   </ImageView>
   <TextView
   android:id="@+id/itemName"
   android:layout_below="@+id/itemImage"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true" >
   </TextView>
  </RelativeLayout>