热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

Android编程重写ViewGroup实现卡片布局的方法

这篇文章主要介绍了Android编程重写ViewGroup实现卡片布局的方法,实例分析新建FlowLayout继承ViewGroup类及设置布局文件实现卡片布局效果的相关技巧,需要的朋友可以参考下

本文实例讲述了Android编程重写ViewGroup实现卡片布局的方法。分享给大家供大家参考,具体如下:

实现效果如图

实现思路

1. 重写onMeasure(int widthMeasureSpec, int heightMeasureSpec)设置每个子View的大小

2. 重写onLayout(boolean changed, int l, int t, int r, int b) 设置每个子View的位置

第一步:新建FlowLayout继承ViewGroup

package com.rong.activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
 * 卡片布局
 * 
 * @author 徐荣
 *
 */
public class FlowLayout extends ViewGroup {
  public FlowLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
  @Override
  protected void onLayout(boolean changed, int l, int t, int r, int b) {
    // 当前子View的数量
    int childSize = getChildCount();
    // 获取行宽
    int lineWidth = getMeasuredWidth();
    // 当前是第几行
    int lines = 1;
    // 当前累加的行宽
    int nowLineWidth = 0;
    for (int i = 0; i = lineWidth 则换行
      if (nowLineWidth + childWidth >= lineWidth) {
        nowLineWidth = 0;
        lines = lines + 1;
      }
      // 设置子View的位置
      view.layout(nowLineWidth, childHeight * (lines - 1), nowLineWidth + childWidth, childHeight * lines);
      nowLineWidth = nowLineWidth + childWidth;
      // 如果nowLineWidth >= lineWidth 则换行
      if (nowLineWidth >= lineWidth) {
        nowLineWidth = 0;
        lines = lines + 1;
      }
    }
  }
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    // 设置自己View的大小
    setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    for (int i = 0; i 

第二步:新建布局文件

<&#63;xml version="1.0" encoding="utf-8"&#63;>

  
    

运行!

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。


推荐阅读
author-avatar
莪啝伱在一敧
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有