Android Studio中GridView的使用方法3-1

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值