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.

  1. Start a new project named HelloGridView.
  2. Find some photos you'd like to use, or download these sample images. Save the image files into the project's res/drawable/ directory.
  3. 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 the GridView reference.

  4. Open HelloGridView.java and insert the following code for the onCreate() 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, the GridView is captured from the layout with findViewById(int). The setAdapter() method then sets a custom adapter (ImageAdapter) as the source for all items to be displayed in the grid. The ImageAdapter is created in the next step.

    To do something when an item in the grid is clicked, the setOnItemClickListener() method is passed a new AdapterView.OnItemClickListener. This anonymous instance defines the onItemClick()callback method to show a Toast 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).

  5. Create a new class called ImageAdapter that extends BaseAdapter:
     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 and getCount() 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 new View for each image added to theImageAdapter. When this is called, a View 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, an ImageView 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 to getView() is not null, then the local ImageView is initialized with the recycledView object.

    At the end of the getView() method, the position integer passed into the method is used to select an image from the mThumbIds array, which is set as the image resource for the ImageView.

    All that's left is to define the mThumbIds array of drawable resources.

  6. 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官方教程及示例的更多相关文章

  1. React Native 教程:001 - 如何运行官方控件示例 App

    原文发表于我的技术博客 本文主要讲解了如何运行 React Native 官方控件示例 App,包含了一些 React Native 的基础知识以及相关环境的配置. 原文发表于我的技术博客 React ...

  2. 微信小程序 教程及示例

    作者:初雪链接:https://www.zhihu.com/question/50907897/answer/128494332来源:知乎著作权归作者所有,转载请联系作者获得授权.微信小程序正式公测, ...

  3. OpenGL官方教程——着色器语言概述

    OpenGL官方教程——着色器语言概述 OpenGL官方教程——着色器语言概述 可编程图形硬件管线(流水线) 可编程顶点处理器 可编程几何处理器 可编程片元处理器 语言 可编程图形硬件管线(流水线) ...

  4. 微信公开课发布微信官方教程:教你用好微信JS-SDK接口

    微信公众平台开放JS-SDK(微信内网页开发工具包),说明文档已经有相关使用方法和示例了,很多同学觉得不是很直观,为此微信公开课发布微信官方教程:教你用好微信JS-SDK接口. 1.分享类接口:支持获 ...

  5. 转:Android官方MVP架构示例项目解析

    转自: http://www.infoq.com/cn/articles/android-official-mvp-architecture-sample-project-analysis 作者 吕英 ...

  6. Asp.Net MVC4.0 官方教程 入门指南之三--添加一个视图

    Asp.Net MVC4.0 官方教程 入门指南之三--添加一个视图 在本节中,您需要修改HelloWorldController类,从而使用视图模板文件,干净优雅的封装生成返回到客户端浏览器HTML ...

  7. Asp.Net MVC4.0 官方教程 入门指南之二--添加一个控制器

    Asp.Net MVC4.0 官方教程 入门指南之二--添加一个控制器 MVC概念 MVC的含义是 “模型-视图-控制器”.MVC是一个架构良好并且易于测试和易于维护的开发模式.基于MVC模式的应用程 ...

  8. Spring 官方教程:使用 Restdocs 创建 API 文档

    https://mp.weixin.qq.com/s?__biz=MzU0MDEwMjgwNA==&mid=2247483998&idx=1&sn=6ae5fa795d36b1 ...

  9. DroidParts 中文系列教程(基于官方教程)

    DroidParts中文系列教程(基于官方教程) (一)DroidParts框架概况 2014年4月18日星期五 11:36 他是一个精心构造的安卓框架,包括下面这些基本功能 DI依赖注入,可以注入V ...

随机推荐

  1. 【js】正则表达式豁然开朗

    http://www.jikexueyuan.com/course/809_3.html?ss=1 小括号,中括号 中括号:[] ,它表示里面的字符任选一个 比如[abcd]+,就表示abcd这四个字 ...

  2. 【iOS】屏幕旋转,屏幕自适应方向变化

    1. iOS有四个方向的旋转,为了保证自己的代码能够支持旋转,我们必须首先处理一个函数: - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInter ...

  3. D3js

    http://d3js.org http://blog.csdn.net/lzhlzz/article/details/27497157

  4. select * from table where 1=1

    转自:http://www.dzwebs.net/2418.html 我们先来看看这个语句的结果:select * from table where 1=1,其中where 1=1,由于1=1永远是成 ...

  5. 常见的装置与其在Linux当中的档名

    需要特别留意的是硬盘机(不论是IDE/SCSI/U盘都一样),每个磁碟机的磁盘分区(partition)不同时, 其磁碟档名还会改变呢!下一小节我们会介绍磁盘分区的相关概念啦!需要特别注意的是磁带机的 ...

  6. UAP如何根据DeviceFamily显示不同的页面

    背景 微软推出UAP 推荐使用响应式的UI,但是难免遇到一些特殊情况需要使用不同的Page来在不同的设备显示. 微软目前最新的VS2015在10074上安装后能够支持这个功能特性,只是暂时没有文档介绍 ...

  7. Zabbix实现告警分级

    Zabbix中trigger的severity的值定义了trigger的不同严重程度,其中severity默认的6个值为 Not classified, Information, Warning, A ...

  8. javascript基础之客户端事件驱动

    我们知道,面向对象发展起来后,“一夜之间”,几乎所有的语言都能基于对象了,JavaScript也是基于对象的语言.用户在浏览器上的行为称作“事件”,之后引发的一系列动作,比如弹窗啦,改变浏览器大小啦, ...

  9. 2140: 稳定婚姻 - BZOJ

    Description 我国的离婚率连续7年上升,今年的头两季,平均每天有近5000对夫妇离婚,大城市的离婚率上升最快,有研究婚姻问题的专家认为,是与简化离婚手续有关. 25岁的姗姗和男友谈恋爱半年就 ...

  10. 学习Ember遇到的一些问题

    1.在模板中不能省略结束标签: 在Ember的模板中,如果省略结束标签的话,会有好多无解的问题(可能是:不更新.更新后结构不对.model和view不同步等),苦苦找了很久.... 2.childVi ...