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

相关文章

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Conda虚拟环境的复制和迁移的四种方法实现

《Conda虚拟环境的复制和迁移的四种方法实现》本文主要介绍了Conda虚拟环境的复制和迁移的四种方法实现,包括requirements.txt,environment.yml,conda-pack,... 目录在本机复制Conda虚拟环境相同操作系统之间复制环境方法一:requirements.txt方法

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja