GridView实现
layoutChildrenView(){
int childrenCount = listData.size();
int singleWidth = (totalWidth - gap * (3 - 1)) / 3;
int singleHeight = singleWidth;
//根据子视图数量上限
ViewGroup.LayoutParams params = getLayoutParams();
params.height = singleHeight * rows + gap * (rows - 1);
setLayoutParams(params);
for (int i = 0; i < childrenCount; i++) {
CustomImageView childrenView = (CustomImageView) getChildAt(i);
childrenView.setImageUrl(((Image) listData.get(i)).getUrl());
int[] position = findPosition(i);
int left = (singleWidth + gap) * position[1];
int top = (singleHeight + gap) * position[0];
int right = left + singleWidth;
int 底部 = 顶部 + singleHeight;
childrenView.layout(左、上、右、下);
}public void setImagesData(List<Image> 列表) {
if (lists == null ||lists.isEmpty()) {
返回;
}
//初始化布置
generateChildrenLayout(lists.size());
//这里做1个重用view的处理
if (listData == null) {
int i = 0;
而 (i < 列表.大小()) {
CustomImageView iv = generateImageView();
addView(iv,generateDefaultLayoutParams());
我++;
}
} 别的 {
int oldViewCount = listData.size();
int newViewCount = list.size();
如果 (oldViewCount > newViewCount) {
removeViews(newViewCount - 1, oldViewCount - newViewCount);
} else if (oldViewCount < newViewCount) {
for (int i = 0; i < newViewCount - oldViewCount; i++) {
CustomImageView iv = generateImageView();
addView(iv,generateDefaultLayoutParams());
}
}
}
listData = 列表;
layoutChildrenView();
- 包 com.weixinninegridlayout;
- 导入 android.content.Context;
- 导入 android.graphics.Color;
- 导入 android.graphics.drawable.ColorDrawable;
- 导入 android.util.AttributeSet;
- 导入 android.view.View;
- 导入 android.view.ViewGroup;
- 导入 android.widget.ImageView;
- 导入 java.util.List;
- /**
- * 由 Pan_ 于 2015/2/2 创建。
- */
- 公共类 NineGridlayout 扩展 ViewGroup {
- /**
- * 图片之间的间隔
- */
- 私人 int 差距 = 5;
- 私有整数列;//
- 私有整数行;//
- 私人列表列表数据;
- 私有整数总宽度;
- 公共 NineGridlayout(上下文上下文){
- 超级(上下文);
- }
- 公共 NineGridlayout(上下文上下文,AttributeSet attrs){
- 超级(上下文,属性);
- ScreenTools screenTools=ScreenTools.instance(getContext());
- totalWidth=screenTools.getScreenWidth()-screenTools.dip2px(80);
- }
- @覆盖
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- }
- @覆盖
- protected void onLayout(boolean 改变,int l,int t,int r,int b) {
- }
- 私有无效 layoutChildrenView(){
- int childrenCount = listData.size();
- int singleWidth = (totalWidth - gap * (3 - 1)) / 3;
- int singleHeight = singleWidth;
- //根据子视图数量上限
- ViewGroup.LayoutParams params = getLayoutParams();
- params.height = singleHeight * rows + gap * (rows - 1);
- setLayoutParams(params);
- for (int i = 0; i < childrenCount; i++) {
- CustomImageView childrenView = (CustomImageView) getChildAt(i);
- childrenView.setImageUrl(((Image) listData.get(i)).getUrl());
- int[] position = findPosition(i);