GridView官方教程及示例
Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter.
For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter.

Example
In this tutorial, you'll create a grid of image thumbnails. When an item is selected, a toast message will display the position of the image.

- Start a new project named HelloGridView.
- Find some photos you'd like to use, or download these sample images. Save the image files into the project's
res/drawable/directory. - Open the
res/layout/main.xmlfile and insert the following:<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>This
GridViewwill fill the entire screen. The attributes are rather self explanatory. For more information about valid attributes, see theGridViewreference. - Open
HelloGridView.javaand insert the following code for theonCreate()method:public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this)); gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(HelloGridView.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}After the
main.xmllayout is set for the content view, theGridViewis captured from the layout withfindViewById(int). ThesetAdapter()method then sets a custom adapter (ImageAdapter) as the source for all items to be displayed in the grid. TheImageAdapteris created in the next step.To do something when an item in the grid is clicked, the
setOnItemClickListener()method is passed a newAdapterView.OnItemClickListener. This anonymous instance defines theonItemClick()callback method to show aToastthat displays the index position (zero-based) of the selected item (in a real world scenario, the position could be used to get the full sized image for some other task). - Create a new class called
ImageAdapterthat extendsBaseAdapter:import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView; public class ImageAdapter extends BaseAdapter {
private Context mContext;
// references to our images
private Integer[] mDatas = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
}; public ImageAdapter(Context c) {
mContext = c;
} public int getCount() {
return mDatas.length;
} public Object getItem(int position) {
return null;
} public long getItemId(int position) {
return ;
} // create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(, ));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(, , , );
} else {
imageView = (ImageView) convertView;
} imageView.setImageResource(mDatas[position]); return imageView;
}
}First, this implements some required methods inherited from
BaseAdapter. The constructor andgetCount()are self-explanatory. Normally,getItem(int)should return the actual object at the specified position in the adapter, but it's ignored for this example. Likewise,getItemId(int)should return the row id of the item, but it's not needed here.The first method necessary is
getView(). This method creates a newViewfor each image added to theImageAdapter. When this is called, aViewis passed in, which is normally a recycled object (at least after this has been called once), so there's a check to see if the object is null. If it is null, anImageViewis instantiated and configured with desired properties for the image presentation:setLayoutParams(ViewGroup.LayoutParams)sets the height and width for the View—this ensures that, no matter the size of the drawable, each image is resized and cropped to fit in these dimensions, as appropriate.setScaleType(ImageView.ScaleType)declares that images should be cropped toward the center (if necessary).setPadding(int, int, int, int)defines the padding for all sides. (Note that, if the images have different aspect-ratios, then less padding will cause more cropping of the image if it does not match the dimensions given to the ImageView.)
If the
Viewpassed togetView()is not null, then the localImageViewis initialized with the recycledViewobject.At the end of the
getView()method, thepositioninteger passed into the method is used to select an image from themThumbIdsarray, which is set as the image resource for theImageView.All that's left is to define the
mThumbIdsarray of drawable resources. - Run the application.
Try experimenting with the behaviors of the GridView and ImageView elements by adjusting their properties. For example, instead of using setLayoutParams(ViewGroup.LayoutParams), try using setAdjustViewBounds(boolean).
GridView官方教程及示例的更多相关文章
- React Native 教程:001 - 如何运行官方控件示例 App
原文发表于我的技术博客 本文主要讲解了如何运行 React Native 官方控件示例 App,包含了一些 React Native 的基础知识以及相关环境的配置. 原文发表于我的技术博客 React ...
- 微信小程序 教程及示例
作者:初雪链接:https://www.zhihu.com/question/50907897/answer/128494332来源:知乎著作权归作者所有,转载请联系作者获得授权.微信小程序正式公测, ...
- OpenGL官方教程——着色器语言概述
OpenGL官方教程——着色器语言概述 OpenGL官方教程——着色器语言概述 可编程图形硬件管线(流水线) 可编程顶点处理器 可编程几何处理器 可编程片元处理器 语言 可编程图形硬件管线(流水线) ...
- 微信公开课发布微信官方教程:教你用好微信JS-SDK接口
微信公众平台开放JS-SDK(微信内网页开发工具包),说明文档已经有相关使用方法和示例了,很多同学觉得不是很直观,为此微信公开课发布微信官方教程:教你用好微信JS-SDK接口. 1.分享类接口:支持获 ...
- 转:Android官方MVP架构示例项目解析
转自: http://www.infoq.com/cn/articles/android-official-mvp-architecture-sample-project-analysis 作者 吕英 ...
- Asp.Net MVC4.0 官方教程 入门指南之三--添加一个视图
Asp.Net MVC4.0 官方教程 入门指南之三--添加一个视图 在本节中,您需要修改HelloWorldController类,从而使用视图模板文件,干净优雅的封装生成返回到客户端浏览器HTML ...
- Asp.Net MVC4.0 官方教程 入门指南之二--添加一个控制器
Asp.Net MVC4.0 官方教程 入门指南之二--添加一个控制器 MVC概念 MVC的含义是 “模型-视图-控制器”.MVC是一个架构良好并且易于测试和易于维护的开发模式.基于MVC模式的应用程 ...
- Spring 官方教程:使用 Restdocs 创建 API 文档
https://mp.weixin.qq.com/s?__biz=MzU0MDEwMjgwNA==&mid=2247483998&idx=1&sn=6ae5fa795d36b1 ...
- DroidParts 中文系列教程(基于官方教程)
DroidParts中文系列教程(基于官方教程) (一)DroidParts框架概况 2014年4月18日星期五 11:36 他是一个精心构造的安卓框架,包括下面这些基本功能 DI依赖注入,可以注入V ...
随机推荐
- 【python】为什么用python
python胶水语言.脚本语言之王,C/C++可以写python的module,标准库里就有用C/C++写的东西,这个跟java的JNI类似. 性能好,易调试: since 91年
- Entity Framework Power Tools安装和使用
Entity Framework Power Tools是一个由EntityFramework开发小组提供的工具,它可以从现有数据库生成Fluent款式的Code First代码. 大致来说,这个工具 ...
- Qt版helloworld
跟学别的编程语言一样,Qt也不例外,一开始就想写一个helloworld.初学Qt十几天,看了一点关于Qt视频的介绍和书上的基础知识,对于Qt写工程的概念有了初步的认识,就代码的形式来说,Qt Cre ...
- UpdateData(false) and UpdateData(true)
数据更新函数: UpdateData(false); 控件的关联变量的值传给控件并改变控件状态(程序--->EXE) UpdateData(true); 控件的状态传给其关联的变量(EXE--- ...
- cocos3.2中如何创建一个场景
1.可以将一些比较通用的东西放到Common.h中,这是一个.h文件,必须手动添加,且保证在classes目录里 #ifndef __COMMON_H__ #define __COMMON_H__ # ...
- JAVASCRIPT、ANDROID、C#分别实现普通日期转换多少小时前、多少分钟前、多少秒
貌似最近很流行这个,就写了个js函数实现之 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> ...
- adb 选择设备
在adb中有多个设备时,可以先adb devices列举出设备,然后可以通过adb -s <设备名> [其他参数] 对某个设备进行操作. 例如: adb -s 0123456789ABC ...
- Eclipse配置默认的编码集为utf-8
既然开了博,那就来点有用的. 可以使用下面的方法,让Eclipse对所有的项目里所有文件都按照指定的编码解析. Eclipse安装目录下有一个eclipse.ini文件, 用记事本打开即可,在最后一行 ...
- 解决在ubuntu下requests 无法找到模块packages
我明明用pip install requests安装成功了,但是依然报下面的错 错误1 requests.packages.urllib3.disable_warnings()AttributeErr ...
- .NET4安装总进度一直不动的解决办法
在安装.NET4时遇到上面的进度在动,而安装进度一直停在0,解决办法: 禁止并关闭Window Update服务,重新运行安装程序. 关闭服务:控制面板->管理工具->服务->Win ...