我的Android学习之路01-GridView

来源:互联网 发布:网络错误代码10071 编辑:程序博客网 时间:2024/06/08 08:54
这个假期开始着手学习android,之前了解过一些简单的概念,也做过一些简单的应用。但都拿不出手。这个暑假,突然有了一个做一款给外国人介绍中国啤酒的软件,决定一步一步给他实现,在实现过程中学习android,岂不美哉。


我的第一个问题,是关于视图的,我心里的app界面大概是现在烂大街的视图,就像淘宝京东那样的。我觉得应该先使用GridView视图。于是开始学习GridView的知识。
首先了解了网格视图的使用场景,GridView的排列方式与矩阵类似,当屏幕上有很多元素(文字、图片或其他元素)需要按矩阵格式进行显示时(如下图),就可以使用GridView控件来实现。
![]({{site.baseurl}}/_posts/timg%20(1).jpg)
官方给出的GridView的定义是:A view that shows items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.


它的常用xml属性如下:

其中,android:columnWidth[int]用于设置每列的宽度;android:gravity[int]用于设置每个网格的比重;android:horizontalSpacing[int]用于设置网格之间列的默认水平距离;android:numColumn[int]用于设置列数;android:stretchMode[int]用于设置列应该以何种方式填充可用空间;android:verticalSpacing[int]用于设置网格之间行的默认垂直距离。
下面我来一步一步地跟着官方的tutorial,首先先定义一个ImageAdapter,继承了BaseAdapter,在ImageAdapter中声明一个整形数组,存储图片资源的ID号,接着写了一个getView方法,将GridView下的ItemView赋值,而值就是图片的id和文字。


public class ImageAdapter extends BaseAdapter {    private Context mContext;    public ImageAdapter(Context c) {        mContext = c;    }    public int getCount() {        return mThumbIds.length;    }    public Object getItem(int position) {        return null;    }    public long getItemId(int position) {        return 0;    }    // 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(85, 85));            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);            imageView.setPadding(8, 8, 8, 8);        } else {            imageView = (ImageView) convertView;        }        imageView.setImageResource(mThumbIds[position]);        return imageView;    }    // references to our images    private Integer[] mThumbIds = {            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    };}




看了另外的文章,发现有利用LayoutInflater传递数组上下文的方法,对这个LayoutInflater不是很了解,打算进一步了解下。
原创粉丝点击