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.xml
file 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
GridView
will fill the entire screen. The attributes are rather self explanatory. For more information about valid attributes, see theGridView
reference. - Open
HelloGridView.java
and 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.xml
layout is set for the content view, theGridView
is 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. TheImageAdapter
is 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 aToast
that 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
ImageAdapter
that 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 newView
for each image added to theImageAdapter
. When this is called, aView
is 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, anImageView
is 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
View
passed togetView()
is not null, then the localImageView
is initialized with the recycledView
object.At the end of the
getView()
method, theposition
integer passed into the method is used to select an image from themThumbIds
array, which is set as the image resource for theImageView
.All that's left is to define the
mThumbIds
array 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 学习教程
<Core Python Programming>勘误参考表 http://starship.python.net/crew/wesc/cpp/errata2.htm 笨办法学 Pytho ...
- iOS中引用计数内存管理机制分析
在 iOS 中引用计数是内存的管理方式,虽然在 iOS5 版本中,已经支持了自动引用计数管理模式,但理解它的运行方式有助于我们了解程序的运行原理,有助于 debug 程序. 操作系统的内存管理分成堆和 ...
- linux第四周作业
一.用户态内核态与中断 1.库函数把内核调用封装起来. 2.区分内核态和用户态是为了让系统更稳定.Linux里吧用户态定位3级,把内核态定位0级. 3.中断处理就是从用户态进入内核态的主要方法,系统调 ...
- ruby condition
class.new 新建class.find 查询class.destroy 删除 变量查询a="hahaha"Product.find(:all,:conditions=> ...
- Useful related java API for Android
Language_suport and Other Language-Oriented API: strings,exceptions, threads, #java.lang.* offers th ...
- Google history
传说,硅谷的公司在和微软的竞争中一直处于下风,不论在市场,人才,还是在打官司上,直到婴儿巨人Baby Giant谷歌的出现,历史才出现前所未有的改变.Google以一个强大的挑战者的身份出现在人们的视 ...
- 2463: [中山市选2009]谁能赢呢?- BZOJ
Description小明和小红经常玩一个博弈游戏.给定一个n×n的棋盘,一个石头被放在棋盘的左上角.他们轮流移动石头.每一回合,选手只能把石头向上,下,左,右四个方向移动一格,并且要求移动到的格子之 ...
- 【BZOJ】【3759】Hungergame饥饿游戏
博弈论/高斯消元 如果没有打开箱子这个操作,那么就是一个很裸的Nim游戏…… 但是有了打开箱子这个操作,就变得蛋疼了T_T 首先我们可以想到一种直接的做法:打开所有箱子,当然如果此时所有a[i]的xo ...
- maven+springMVC+mybatis+junit详细搭建过程 ***
springMVC+mybatis框架搭建 在上一遍博客中以及讲诉了新建maven项目的流程,现在紧跟上一遍文章,接着搭建spring项目 首先我们先要弄清搭建项目的一般流程,需要注意哪些方面,想要什 ...
- memcached+php客户端
连接memcached <?php $mem = new Memcache; $mem->connect('localhost',11211) or die("connected ...