自定义ViewGroup实现标签换行(动态创建标签

2024-05-14 10:18

本文主要是介绍自定义ViewGroup实现标签换行(动态创建标签,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

转载请注明:http://blog.csdn.net/u010419467/article/details/47256041

具体实现步骤: 
1.继承ViewGroup,实现三个构造方法 
2.通过generateLayoutParams给自定义的控件指定参数 
3.实现onMeasure方法 
       a.在这个方法里面首先要做是要知道自己的大小,onMeasure方法会通过父类获取具体的模式和大小。通过getMode方法获得模式(三种模式就不详细说了),然后通过getSize方法获取具体的尺寸。 
       b.通过遍历子控件得到ViewGroup显示时的高度。当子控件(即标签)的宽度之和大于父控件的时候开启行并累加高度 
       c.setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth  
                : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight  
                : height);  方法确定我们ViewGroup最终的大小 
4.重写onLayout方法 
        a.同样的需要遍历子控件,根据宽度控制是否换行。并将每一行的空间用一个列表记录下来,并记录高度从而决定下一行需要显示的位置。 
        b.上面已经将标签以行为单位分别放到适当的list里面。这里就是将list里面的控件显示出来。说到底其实就是一个道理:不管通过什么样的算法,只要知道子控件正确的显示位置即可。 
        c.确定完位置后调用child.layout(lc, tc, rc, bc);  方法将它画出来即可。需要注意的地方是最后一行我们需要特殊处理。通过上面的判断我们实际的最后一行是永远不会大于ViewGroup的宽度的,而这一行的高度同样需要记录下来 

完整的代码如下: 

public class MyFlowLayout extends ViewGroup {public MyFlowLayout(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// TODO Auto-generated constructor stub}public MyFlowLayout(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stub}public MyFlowLayout(Context context) {super(context);// TODO Auto-generated constructor stub}public void setData(String[] data,Context context,int textSize,int pl,int pt,int pr,int pb,int ml,int mt,int mr,int mb){createChild(data,context,textSize, pl, pt, pr, pb, ml, mt, mr, mb);}public void setData(List<String> data,Context context,int textSize,int pl,int pt,int pr,int pb,int ml,int mt,int mr,int mb){String[] mydata = null;if(data!=null){int length = data.size();mydata = new String[length];for(int i = 0 ; i<length;i++){mydata[i] = data.get(i);}}setData(mydata,context, textSize,pl, pt, pr, pb, ml, mt, mr, mb);}private void createChild(String[] data, Context context,int textSize,int pl,int pt,int pr,int pb,int ml,int mt,int mr,int mb){int size = data.length;for(int i = 0;i<size;i++){String text = data[i];TextView btn = new TextView(context);btn.setClickable(true);btn.setGravity(Gravity.CENTER);btn.setText(text);btn.setTextSize(textSize);btn.setPadding(dip2px(context, pl),dip2px(context, pt),dip2px(context, pr),dip2px(context, pb));
//			btn.setTextColor(0xff67c530);btn.setTextColor(getResources().getColorStateList(R.color.selector_button_tc));btn.setBackgroundResource(R.drawable.mark_green);MarginLayoutParams params = new MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT,MarginLayoutParams.WRAP_CONTENT);params.setMargins(ml, mt, mr, mb);btn.setLayoutParams(params);btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {//clickMark(btnText);}});this.addView(btn);}}interface MarkClickListener{}/** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */  private int dip2px(Context context, float dpValue) {  final float scale = context.getResources().getDisplayMetrics().density;  return (int) (dpValue * scale + 0.5f);  }  @Overridepublic LayoutParams generateLayoutParams(AttributeSet attrs) {return new MarginLayoutParams(getContext(), attrs);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);int widthMode = MeasureSpec.getMode(widthMeasureSpec);int heightMode = MeasureSpec.getMode(heightMeasureSpec);int widthSize = MeasureSpec.getSize(widthMeasureSpec);int heightSize = MeasureSpec.getSize(heightMeasureSpec);int childCount = getChildCount();int lineWidth = 0;int lineHeight = 0;int width = 0;//warpcontet是需要记录的宽度int height = 0;for(int i = 0 ; i< childCount;i++){View child = getChildAt(i);// 测量每一个child的宽和高 measureChild(child, widthMeasureSpec, heightMeasureSpec);MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();int childWidth = child.getMeasuredWidth()+lp.leftMargin+lp.rightMargin;int childHeight = child.getMeasuredHeight()+lp.topMargin+lp.bottomMargin;if(lineWidth+childWidth>widthSize){width = Math.max(lineWidth, childWidth);//这种情况就是排除单个标签很长的情况lineWidth = childWidth;//开启新行height += lineHeight;//记录总行高lineHeight = childHeight;//因为开了新行,所以这行的高度要记录一下}else{lineWidth += childWidth;lineHeight = Math.max(lineHeight, childHeight); //记录行高}// 如果是最后一个,则将当前记录的最大宽度和当前lineWidth做比较  if (i == childCount - 1)  {  width = Math.max(width, lineWidth);  //宽度height += lineHeight;  //}}setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? widthSize  : width, (heightMode == MeasureSpec.EXACTLY) ? heightSize  : height);}/** * 存储所有的View,按行记录 */  private List<List<View>> mAllViews = new ArrayList<List<View>>();  /** * 记录每一行的最大高度 */  private List<Integer> mLineHeight = new ArrayList<Integer>();//onLayout中完成对所有childView的位置以及大小的指定@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {mAllViews.clear();  //清空子控件列表mLineHeight.clear();  //清空高度记录列表int width = getWidth();//得到当前控件的宽度(在onmeasure方法中已经测量出来了)int childCount = getChildCount();// 存储每一行所有的childView  List<View> lineViews = new ArrayList<View>();  int lineWidth = 0;  //行宽int lineHeight = 0; //总行高for(int i = 0 ; i<childCount;i++){View child = getChildAt(i);MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();//得到属性参数int childWidth = child.getMeasuredWidth();int childHeight = child.getMeasuredHeight();// 如果已经需要换行  if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth > width)  //大于父布局的宽度{  // 记录这一行所有的View以及最大高度  mLineHeight.add(lineHeight);  // 将当前行的childView保存,然后开启新的ArrayList保存下一行的childView  mAllViews.add(lineViews);  lineWidth = 0;// 重置行宽  lineViews = new ArrayList<View>();  }  /** * 如果不需要换行,则累加 */  lineWidth += childWidth + lp.leftMargin + lp.rightMargin;  lineHeight = Math.max(lineHeight, childHeight + lp.topMargin  + lp.bottomMargin);  lineViews.add(child);  }// 记录最后一行  (因为最后一行肯定大于父布局的宽度,所以添加最后一行是必要的)mLineHeight.add(lineHeight);  mAllViews.add(lineViews);  int left = 0;int top = 0;int lineNums = mAllViews.size();for(int i = 0;i<lineNums;i++){// 每一行的所有的views  lineViews = mAllViews.get(i);  // 当前行的最大高度  lineHeight = mLineHeight.get(i);  for(int j = 0 ;j < lineViews.size() ; j++){View lineChild = lineViews.get(j);if(lineChild.getVisibility() == View.GONE){continue;}MarginLayoutParams lp = (MarginLayoutParams) lineChild.getLayoutParams();//开始画标签了。左边和上边的距离是要根据累计的数确定的。int lc = left + lp.leftMargin;int tc = top+lp.topMargin;int rc = lc+lineChild.getMeasuredWidth();int bc = tc+lineChild.getMeasuredHeight();lineChild.layout(lc, tc, rc, bc);left += lineChild.getMeasuredWidth() + lp.rightMargin + lp.leftMargin;}left = 0;//将left归零top = lineHeight;}}




调用方法:

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);MyFlowLayout myview = (MyFlowLayout) findViewById(R.id.myview);String[] myData = {"one","two","dkfjdkf","kdfkdfj","jdkfdfkjdkfdkfkdkdfj","kdjkfdjkjkjskkjkd"};myview.setData(myData, this, 15, 10, 10, 10, 10, 10, 10, 10, 10);}


下载连接:点击打开链接

希望爱好编程的小伙伴能加这个群,互相帮助,共同学习。群号: 141877583


下面有附件中不需要积分

这篇关于自定义ViewGroup实现标签换行(动态创建标签的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/988472

相关文章

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核