GridView 各项平分空间

转自:http://www.jb51.net/article/68445.htm

如果你想在设计阶段就看到宫格效果的话,你可以在该空间的Tag属性上设置行列个数。比如我想看到3x3的宫格样子的话就设置成"3,3",如下图,当然你也可以在代码中使用setRowNum()和setColNum()来进行设置,但是请在设置适配器前调用这两个方法。

package com.broadthinking.bledemoHB.view.ui;

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;

/**
* Created by jeremy on 2015/7/14.
*/
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.MATCH_PARENT, LayoutParams.MATCH_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.MATCH_PARENT, LayoutParams.MATCH_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;
}
}
效果图
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值