在日常手机app的使用中,出现频率最高的便是ListView和GridView。ListView的例子是微信主界面,而GridView的例子则是支付宝的主界面,不明白的小伙伴打开手机便一目了然。然而这两个控件同时也称成为最难使用的控件,由于两个控件使用方法完全相同,今天博主以GridView为例,讲一讲我和它的故事。
1. 小白初探--使用SimpleAdapter加载本地资源
单纯学习使用GridView还是很简单的,只需要使用一个数据适配器将所需要显示的数据资源(包括图像和文本),与布局文件中的控件连接起来即可。
数据适配器
// activity_gridview.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="edu.sjtu.helloworld.app.GridviewActivity"
android:id="@+id/grid">
android:id="@+id/grid_test"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
// grid_item.xml
android:orientation="vertical"
android:gravity="center"
android:background="#ffffff"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/img_item"
android:src="@mipmap/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
android:id="@+id/txt_item"
android:textColor="#000000"
android:text="文字区域"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
// GridViewActivity.java
package edu.sjtu.helloworld.app;
import android.content.Intent;
import android.net.Uri;