很久没有进行我的Android学习之旅了,今天抽空继续。
简单一点吧,就瞧瞧那个Grid的效果,Android提供了一个GridView,不过从APIDemo中看来,它似乎与PC上的GRID差别还是挺大的,更像那个IconView的感觉。不知道Android中如何实现表格界面?虽然在移动终端上,表格一般不会有谁使用,大家似乎更倾向于使用ListView,而Android对于ListView则有更简单的实现ListActivity。
废话不说,还是自己写几句代码来实验一下。
<GridViewid="@+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:verticalSpacing="10"
android:horizontalSpacing="10"
android:numColumns="auto_fit"
android:columnWidth="60"
android:stretchMode="columnWidth"
android:gravity="center"
/>
从描述文件中的这些属性来看,与表格非常类似,除了padding和spacing以外,它还多了那个gravity,这里是center表示单元格中的内容居中放,在类GridView中也提供了方法setGravity(int)来实现这个效果。
接着,我们沿用以前那个fillMaps方法来构造SimpleAdapter,以前将这个adapter赋给ListActivity,现在同样的Adapter,却是赋给了GridView,效果又会是怎样呢?
List<HashMap<String,String>>items=fillMaps();
GridViewgrd=(GridView)this.findViewById(R.id.grid);
SimpleAdapteradapter=newSimpleAdapter(this,items,R.layout.list_row,newString[]...{"name"},newint[]...{R.id.item});
grd.setAdapter(adapter);
我觉得GridView并不象表格,倒更象IconView,下面试试用图像作为GridView的内容。现在,不能用简单Adapter了,得自己弄一个ImageAdapter,就让它衍生于BaseAdapter类吧。

publicclassImageAdapterextendsBaseAdapter...{
//这是资源ID的数组
privateInteger[]mThumbIds=...{
R.drawable.a,R.drawable.b,R.drawable.c,
R.drawable.d,R.drawable.e,R.drawable.f,
R.drawable.g,R.drawable.h,R.drawable.i
};

publicImageAdapter(Contextc)...{
mContext=c;
}

publicintgetCount()...{
returnmThumbIds.length;
}

publicObjectgetItem(intposition)...{
returnposition;
}

publiclonggetItemId(intposition)...{
returnposition;
}

publicViewgetView(intposition,ViewconvertView,ViewGroupparent)...{
ImageViewi=newImageView(mContext);
//设置图像源于资源ID。
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setBackground(android.R.drawable.picture_frame);
returni;
}
privateContextmContext;
}
很简单,只要重载几个方法就可以了,关键是那个getView方法,它负责构建出每个单元格中的对象实例。这里我们构造的是一个ImageView实例。
然后就是同样的将这个Adapter赋给GridView即可,大家可以看看效果,注意在做这个例子前,先放几个小图片到res/drawable目录下,buildproject一下就可以得到那个R.drawable.a了(这里的a是图像文件名,如a.png)。
在getView方法中我们使用了ImageView类,这又是一个widget。除了上面用到的几个方法以外,还有以下几个方法值得注意:
与图像来源有关的方法,我们只用了资源文件的方式。
publicvoidsetImageBitmap(Bitmapbm)
publicvoidsetImageDrawable(Drawabledrawable)
publicvoidsetImageResource(intresid)
publicvoidsetImageURI(ContentURIuri)
图像效果的操作。
//颜色过滤
publicvoidsetColorFilter(intcolor,Modemode)
//矩阵变换
publicvoidsetImageMatrix(Matrixmatrix)
//透明度
publicvoidsetAlpha(intalpha)
具体的使用可以参考API,动手试一下就差不多了。
本文通过实践介绍了Android中的GridView组件,展示了如何使用GridView展示列表和图像,包括设置布局属性、使用SimpleAdapter及自定义BaseAdapter。
7066

被折叠的 条评论
为什么被折叠?



