自定义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

相关文章

python实现svg图片转换为png和gif

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录python实现svg图片转换为png和gifpython实现图片格式之间的相互转换延展:基于Py

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.

Java的栈与队列实现代码解析

《Java的栈与队列实现代码解析》栈是常见的线性数据结构,栈的特点是以先进后出的形式,后进先出,先进后出,分为栈底和栈顶,栈应用于内存的分配,表达式求值,存储临时的数据和方法的调用等,本文给大家介绍J... 目录栈的概念(Stack)栈的实现代码队列(Queue)模拟实现队列(双链表实现)循环队列(循环数组

C++如何通过Qt反射机制实现数据类序列化

《C++如何通过Qt反射机制实现数据类序列化》在C++工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作,所以本文就来聊聊C++如何通过Qt反射机制实现数据类序列化吧... 目录设计预期设计思路代码实现使用方法在 C++ 工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作。由于数据类

Python实现图片分割的多种方法总结

《Python实现图片分割的多种方法总结》图片分割是图像处理中的一个重要任务,它的目标是将图像划分为多个区域或者对象,本文为大家整理了一些常用的分割方法,大家可以根据需求自行选择... 目录1. 基于传统图像处理的分割方法(1) 使用固定阈值分割图片(2) 自适应阈值分割(3) 使用图像边缘检测分割(4)

Android实现在线预览office文档的示例详解

《Android实现在线预览office文档的示例详解》在移动端展示在线Office文档(如Word、Excel、PPT)是一项常见需求,这篇文章为大家重点介绍了两种方案的实现方法,希望对大家有一定的... 目录一、项目概述二、相关技术知识三、实现思路3.1 方案一:WebView + Office Onl

C# foreach 循环中获取索引的实现方式

《C#foreach循环中获取索引的实现方式》:本文主要介绍C#foreach循环中获取索引的实现方式,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、手动维护索引变量二、LINQ Select + 元组解构三、扩展方法封装索引四、使用 for 循环替代

Spring Security+JWT如何实现前后端分离权限控制

《SpringSecurity+JWT如何实现前后端分离权限控制》本篇将手把手教你用SpringSecurity+JWT搭建一套完整的登录认证与权限控制体系,具有很好的参考价值,希望对大家... 目录Spring Security+JWT实现前后端分离权限控制实战一、为什么要用 JWT?二、JWT 基本结构

Java实现优雅日期处理的方案详解

《Java实现优雅日期处理的方案详解》在我们的日常工作中,需要经常处理各种格式,各种类似的的日期或者时间,下面我们就来看看如何使用java处理这样的日期问题吧,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言一、日期的坑1.1 日期格式化陷阱1.2 时区转换二、优雅方案的进阶之路2.1 线程安全重构2

Android实现两台手机屏幕共享和远程控制功能

《Android实现两台手机屏幕共享和远程控制功能》在远程协助、在线教学、技术支持等多种场景下,实时获得另一部移动设备的屏幕画面,并对其进行操作,具有极高的应用价值,本项目旨在实现两台Android手... 目录一、项目概述二、相关知识2.1 MediaProjection API2.2 Socket 网络