我的Android学习之路01-GridView

这个假期开始着手学习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不是很了解,打算进一步了解下。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值