AndroidUI系列-ViewGroup流式布局

2024-02-29 07:32

本文主要是介绍AndroidUI系列-ViewGroup流式布局,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

很多时候,我们会遇见各种各样的需求,流式布局算是非常常见的一种。像各种菜单啊,展示之类的。其实这个很简单,可以自己手写一个,顺便练练自定义控件。先看看效果。

这里写图片描述

那么先来分析一下,满足这个需求,应该需要做哪些准备。

这里写图片描述

就像备注写的一样,
首先需要准备的条件:
一个List<List< View > > 来缓存多少行。
一个List<Integer> 来缓存每一行的高度。
一个List<View> 来缓存每一行的子控件View。
相对于每一行来说,需要一个变量缓存当前行的宽度,一个变量缓存当前行的最大高度。

换行的条件:
当前行的宽度加上下一个子控件的宽度,超过了当前控件允许的最大宽度。那就换行。

那么直接开始撸吧。

package com.example.administrator.flowlayout;import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;import java.util.ArrayList;
import java.util.List;/*** Created by ShuWen on 2017/6/1.*/public class FlowLayout extends ViewGroup {//用于缓存的多少行private List<List<View>> mLineViewsList = new ArrayList<>();//用于缓存每一行最大的高度private List<Integer> mLinesHieights = new ArrayList<>();public FlowLayout(Context context) {super(context);}public FlowLayout(Context context, AttributeSet attrs) {super(context, attrs);}public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}//为了获取子控件的margin属性值@Overridepublic LayoutParams generateLayoutParams(AttributeSet attrs) {return new MarginLayoutParams(getContext(),attrs);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);//获取测量模式int meaWidthMode = MeasureSpec.getMode(widthMeasureSpec);int meaHeightMode = MeasureSpec.getMode(heightMeasureSpec);//获得允许的宽高int meaWidthSize = MeasureSpec.getSize(widthMeasureSpec);int meaHeightSize = MeasureSpec.getSize(heightMeasureSpec);//最后测量的宽高int measuredWidth = 0;int measuredHeight = 0;if (meaHeightMode == MeasureSpec.EXACTLY && meaWidthMode == MeasureSpec.EXACTLY){measuredHeight = meaHeightSize;measuredWidth = meaWidthSize;}else {int iCurLineW = 0;int iCurLineH = 0;int childWidth = 0;int childHeight = 0;int childCount = getChildCount();//用于缓存每一行的子控件List<View> childsList = new ArrayList<>();for (int i = 0; i < childCount; i++) {View childView = getChildAt(i);//测量子控件,获得子控件的宽高和margin值measureChild(childView,widthMeasureSpec,heightMeasureSpec);MarginLayoutParams params = (MarginLayoutParams) childView.getLayoutParams();//自控件的宽高childWidth = params.leftMargin + childView.getMeasuredWidth() + params.rightMargin;childHeight = params.topMargin + childView.getMeasuredHeight() + params.bottomMargin;//当前行的宽度,加上下一个控件的宽度大于允许值,则换行if (childWidth + iCurLineW > meaWidthSize){//换行操作,记录测量的父控件宽高measuredWidth = Math.max(measuredWidth,iCurLineW);measuredHeight += iCurLineH;//保存该行的数据mLineViewsList.add(childsList);mLinesHieights.add(iCurLineH);//重新记录新的一行iCurLineH = childHeight;iCurLineW = childWidth;//开始缓存新一行数据childsList = new ArrayList<>();childsList.add(childView);}else {//未换行操作,记录该行宽高iCurLineH = Math.max(iCurLineH,childHeight);iCurLineW += childWidth;//保存到该行集合childsList.add(childView);}//当该行是最后一行并且需要换行时,进行换行数据处理if (i == childCount - 1){measuredHeight += iCurLineH;measuredWidth = Math.max(measuredWidth,iCurLineW);mLinesHieights.add(iCurLineH);mLineViewsList.add(childsList);}}}setMeasuredDimension(measuredWidth,measuredHeight);}@Overrideprotected void onLayout(boolean b, int i, int i1, int i2, int i3) {int left,top,right,bottom;int curLeft = 0;int curTop = 0;int linesCount = mLineViewsList.size();for (int j = 0; j < linesCount; j++) {List<View> childViews = mLineViewsList.get(j);int childsCount = childViews.size();for (int k = 0; k < childsCount; k++) {View childView = childViews.get(k);MarginLayoutParams params = (MarginLayoutParams) childView.getLayoutParams();left = curLeft + params.leftMargin;top = curTop + params.topMargin;right = left + childView.getMeasuredWidth();bottom = top + childView.getMeasuredHeight();//为子控件布局childView.layout(left,top,right,bottom);curLeft += params.leftMargin + childView.getMeasuredWidth() + params.rightMargin;}curLeft = 0;curTop += mLinesHieights.get(j);}mLinesHieights.clear();mLineViewsList.clear();}public interface onItemClick{void click(View view,int position);}public void setOnItemClickListener(final onItemClick onItemClick){int childCount = getChildCount();for (int i = 0; i < childCount; i++) {View childView = getChildAt(i);final int finalI = i;childView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View view) {onItemClick.click(view, finalI);}});}}
}

其中用到的flag背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><corners android:radius="10dp"/><padding android:bottom="2dp"android:top="2dp"android:right="10dp"android:left="10dp"/><solid android:color="@color/colorPrimary"/>
</shape>

textView的样式.

<style name="text_flag"><item name="android:background">@drawable/flag</item><item name="android:layout_width">wrap_content</item><item name="android:layout_height">wrap_content</item><item name="android:layout_margin">4dp</item><item name="android:textColor">#fff</item></style>

activity的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/activity_main"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.administrator.flowlayout.MainActivity"><com.example.administrator.flowlayout.FlowLayout
        android:id="@+id/flowlayout"android:layout_width="fill_parent"android:layout_height="wrap_content"><TextView
            style="@style/text_flag"android:text="阿萨德 "/><TextView
            style="@style/text_flag"android:text="我阿萨德阿萨德的"/><TextView
            style="@style/text_flag"android:textSize="16sp"android:text="你阿萨德阿萨德的"/><TextView
            style="@style/text_flag"android:textSize="19sp"android:text="阿萨德 阿萨德"/><TextView
            style="@style/text_flag"android:text="阿萨德阿萨德"/><TextView
            style="@style/text_flag"android:text="阿大声道"/><TextView
            style="@style/text_flag"android:text="阿大声道"/><TextView
            style="@style/text_flag"android:text="为全文完请二位"/><TextView
            style="@style/text_flag"android:text="谁是谁"/><TextView
            style="@style/text_flag"android:text="撒大声地"/><TextView
            style="@style/text_flag"android:text="阿大声道"/><TextView
            style="@style/text_flag"android:text="大法师"/><TextView
            style="@style/text_flag"android:text="12123"/><TextView
            style="@style/text_flag"android:text="sadsa"/></com.example.administrator.flowlayout.FlowLayout>
</LinearLayout>

就这么简单,自己撸一遍吧,总能学到一点的。

这篇关于AndroidUI系列-ViewGroup流式布局的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

科研绘图系列:R语言扩展物种堆积图(Extended Stacked Barplot)

介绍 R语言的扩展物种堆积图是一种数据可视化工具,它不仅展示了物种的堆积结果,还整合了不同样本分组之间的差异性分析结果。这种图形表示方法能够直观地比较不同物种在各个分组中的显著性差异,为研究者提供了一种有效的数据解读方式。 加载R包 knitr::opts_chunk$set(warning = F, message = F)library(tidyverse)library(phyl

【生成模型系列(初级)】嵌入(Embedding)方程——自然语言处理的数学灵魂【通俗理解】

【通俗理解】嵌入(Embedding)方程——自然语言处理的数学灵魂 关键词提炼 #嵌入方程 #自然语言处理 #词向量 #机器学习 #神经网络 #向量空间模型 #Siri #Google翻译 #AlexNet 第一节:嵌入方程的类比与核心概念【尽可能通俗】 嵌入方程可以被看作是自然语言处理中的“翻译机”,它将文本中的单词或短语转换成计算机能够理解的数学形式,即向量。 正如翻译机将一种语言

flume系列之:查看flume系统日志、查看统计flume日志类型、查看flume日志

遍历指定目录下多个文件查找指定内容 服务器系统日志会记录flume相关日志 cat /var/log/messages |grep -i oom 查找系统日志中关于flume的指定日志 import osdef search_string_in_files(directory, search_string):count = 0

GPT系列之:GPT-1,GPT-2,GPT-3详细解读

一、GPT1 论文:Improving Language Understanding by Generative Pre-Training 链接:https://cdn.openai.com/research-covers/languageunsupervised/language_understanding_paper.pdf 启发点:生成loss和微调loss同时作用,让下游任务来适应预训

lvgl8.3.6 控件垂直布局 label控件在image控件的下方显示

在使用 LVGL 8.3.6 创建一个垂直布局,其中 label 控件位于 image 控件下方,你可以使用 lv_obj_set_flex_flow 来设置布局为垂直,并确保 label 控件在 image 控件后添加。这里是如何步骤性地实现它的一个基本示例: 创建父容器:首先创建一个容器对象,该对象将作为布局的基础。设置容器为垂直布局:使用 lv_obj_set_flex_flow 设置容器

Java基础回顾系列-第七天-高级编程之IO

Java基础回顾系列-第七天-高级编程之IO 文件操作字节流与字符流OutputStream字节输出流FileOutputStream InputStream字节输入流FileInputStream Writer字符输出流FileWriter Reader字符输入流字节流与字符流的区别转换流InputStreamReaderOutputStreamWriter 文件复制 字符编码内存操作流(

Java基础回顾系列-第五天-高级编程之API类库

Java基础回顾系列-第五天-高级编程之API类库 Java基础类库StringBufferStringBuilderStringCharSequence接口AutoCloseable接口RuntimeSystemCleaner对象克隆 数字操作类Math数学计算类Random随机数生成类BigInteger/BigDecimal大数字操作类 日期操作类DateSimpleDateForma

Java基础回顾系列-第三天-Lambda表达式

Java基础回顾系列-第三天-Lambda表达式 Lambda表达式方法引用引用静态方法引用实例化对象的方法引用特定类型的方法引用构造方法 内建函数式接口Function基础接口DoubleToIntFunction 类型转换接口Consumer消费型函数式接口Supplier供给型函数式接口Predicate断言型函数式接口 Stream API 该篇博文需重点了解:内建函数式