GridView控件的作用是通过网格来显示指定的内容,如图1所示。

图1 GridView控件的使用
从图1中可以看出,GridView控件使用“网格”来显示球星。
1 GridView通过自定义Adapter显示数据
GridView控件的通过自定义Adapter显示数据的方法与《Android Studio中ListView通过自定义Adapter显示数据3-1》中提到的ListView控件相似,分为四个步骤,分别是:定义数据类、定义网格布局、定义Adapter类和设置数据。
1.1 定义数据类
在项目中添加名为“Player”的类,该类中包含了要在GridView中显示的信息,即“姓名”和“头像”,代码如下所示。
public class Player {
private int face;
private String name;
public Player(String name, int face)
{
this.name = name;
this.face = face;
}
public String getName()
{
return name;
}
public int getFace()
{
return face;
}
}
其中,变量name是“姓名”,变量“face”是头像的资源ID。
1.2 定义网格布局
在项目中添加线性布局文件,用来定义网格的布局,代码如下所示。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/gridview_item_iv1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="40sp"
android:gravity="center"
android:textColor="#FF0000"
android:id="@+id/gridview_item_tv1"/>
</LinearLayout>
在该布局文件中,包含了两个控件,分别是用于显示头像的ImageView控件和用于显示姓名的TextView控件,该布局的orientation设置为垂直,即vertical。

930

被折叠的 条评论
为什么被折叠?



