Android实现九宫格(GridView中各项平分空间)的方法
程序员文章站
2023-11-08 14:26:28
本文实例讲述了android实现九宫格(gridview中各项平分空间)的方法。分享给大家供大家参考。具体如下:
项目需要做一个九宫格(也不一定是9的,4宫格、16宫格、...
本文实例讲述了android实现九宫格(gridview中各项平分空间)的方法。分享给大家供大家参考。具体如下:
项目需要做一个九宫格(也不一定是9的,4宫格、16宫格、4x3宫格。。。),封了 一个宫格,它能够根据为它分配的空间来自动的调节宫中各项的尺寸。
从tablelayout集成来的,因此如果你直接在设计器上使用该封装的话需要把它自动加进去的那几个tablerow删除一下。
类名为advancedgridview,代码如下:
import android.content.context; import android.util.attributeset; import android.view.view; import android.widget.baseadapter; import android.widget.button; import android.widget.tablelayout; import android.widget.tablerow; /** * advancedgridview * @author robintang * @time 2012-10-15 */ public class advancedgridview extends tablelayout { // private static final string tag = "advancedgridview"; private int rownum = 0; // row number private int colnum = 0; // col number private baseadapter adapter = null; private context context = null; public advancedgridview(context context) { super(context); initthis(context, null); } public advancedgridview(context context, attributeset attrs) { super(context, attrs); initthis(context, attrs); } private void initthis(context context, attributeset attrs) { this.context = context; if (this.gettag() != null) { string atb = (string) this.gettag(); int ix = atb.indexof(','); if (ix > 0) { rownum = integer.parseint(atb.substring(0, ix)); colnum = integer.parseint(atb.substring(ix+1, atb.length())); } } if (rownum <= 0) rownum = 3; if (colnum <= 0) colnum = 3; if(this.isineditmode()){ this.removeallviews(); for(int y=0; y<rownum; ++y){ tablerow row = new tablerow(context); row.setlayoutparams(new layoutparams(layoutparams.fill_parent, layoutparams.fill_parent, 1.0f)); for(int x=0; x<colnum; ++x){ view button = new button(context); row.addview(button, new tablerow.layoutparams (layoutparams.match_parent, layoutparams.match_parent, 1.0f)); } this.addview(row); } } } public baseadapter getadapter() { return adapter; } public void setadapter(baseadapter adapter) { if(adapter != null){ if(adapter.getcount() < this.rownum*this.colnum){ throw new illegalargumentexception("the view count of adapter is less than this gridview's items"); } this.removeallviews(); for(int y=0; y<rownum; ++y){ tablerow row = new tablerow(context); row.setlayoutparams(new layoutparams(layoutparams.fill_parent, layoutparams.fill_parent, 1.0f)); for(int x=0; x<colnum; ++x){ view view = adapter.getview(y*colnum+x, this, row); row.addview(view, new tablerow.layoutparams (layoutparams.match_parent, layoutparams.match_parent, 1.0f)); } this.addview(row); } } this.adapter = adapter; } public int getrownum() { return rownum; } public void setrownum(int rownum) { this.rownum = rownum; } public int getcolnum() { return colnum; } public void setcolnum(int colnum) { this.colnum = colnum; } }
如果你想在设计阶段就看到宫格效果的话,你可以在该空间的tag属性上设置行列个数。比如我想看到3x3的宫格样子的话就设置成"3,3",如下图,当然你也可以在代码中使用setrownum()和setcolnum()来进行设置,但是请在设置适配器前调用这两个方法。
希望本文所述对大家的android程序设计有所帮助。
上一篇: 猪肉茶树菇的做法介绍