AndroidUI系列 - ViewGroup实现瀑布流

2024-02-29 07:32

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

其实瀑布流现在用的越来越少了,更多的是使用MD的风格了。风靡一时的瀑布流现在渐渐地开始退居后幕了。不过,瀑布流也是个不错的自定义控件练习方式。相对简单的实现逻辑,可以帮助更好的更快的上手ViewGroup的自定义,以及onMeasure和onLayout等方法的理解和学习。先看看效果。

这里写图片描述

那么再来看看,需要考虑些什么。
这里写图片描述

很简单的逻辑,外围能滑动,因为加了一层ScollView,当然也可以不加,为了方便就加了。
直接贴代码。

package com.example.administrator.myapplication.flow;import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;import com.example.administrator.myapplication.R;/*** Created by ShuWen on 2017/6/9.*/public class WaterFallLayout extends ViewGroup {private int mTop[];private int mColNumber = 3;//默认3列private int mHorozontalSpace = 20;//每列间隔20pxprivate int mVerticalSpace = 20;//每行之间private int childWidth = 0;private int maxHeight = 0;private int minColNumber = 0;public WaterFallLayout(Context context) {super(context);init(context,null);}public WaterFallLayout(Context context, AttributeSet attrs) {super(context, attrs);init(context,attrs);}public WaterFallLayout(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);init(context,attrs);}private void init(Context context, AttributeSet attrs){TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.WaterFallLayout);mColNumber = typedArray.getInt(R.styleable.WaterFallLayout_mColNumber,3);mHorozontalSpace = DensityUtil.dip2px(context,typedArray.getDimension(R.styleable.WaterFallLayout_mHorozontalSpace,20));mVerticalSpace = DensityUtil.dip2px(context,typedArray.getDimension(R.styleable.WaterFallLayout_mVerticalSpace,20));mTop = new int[mColNumber];}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);//测量模式int widthMeasureMode = MeasureSpec.getMode(widthMeasureSpec);int heightMeasureMode = MeasureSpec.getMode(heightMeasureSpec);//默认大小int widthMeasureSize = MeasureSpec.getSize(widthMeasureSpec);int heightMeasureSize = MeasureSpec.getSize(heightMeasureSpec);//测量之后的宽高int measuredWidth = 0;int measuredHeight = 0;//测量所有子控件for (int i = 0; i < getChildCount(); i++) {View view = getChildAt(i);measureChild(view,widthMeasureSpec,heightMeasureSpec);}//计算每列的宽childWidth = (widthMeasureSize - mColNumber * mHorozontalSpace) / 3;//计算控件的宽 若设置了确定的大小,就采用设置大小if (widthMeasureMode == MeasureSpec.EXACTLY) {measuredWidth = widthMeasureSize;} else {if (getChildCount() > mColNumber) {measuredWidth = widthMeasureSize;} else {measuredWidth = childWidth * getChildCount() + (getChildCount() - 1) * mHorozontalSpace;}}//计算控件的高 若设置了确定的大小,就采用设置大小if (heightMeasureMode == MeasureSpec.EXACTLY) {measuredHeight = heightMeasureSize;} else {measuredHeight = getMaxHeight();}setMeasuredDimension(measuredWidth, measuredHeight);}@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {int left, top, right, bottom;//再次布局时,清除上次缓存数据clearTop();int childCount = getChildCount();for (int i = 0; i < childCount; i++) {View viewChild = getChildAt(i);int measuredHeight = viewChild.getMeasuredHeight();int measuredWidth = viewChild.getMeasuredWidth();int childHeight = measuredHeight * childWidth / measuredWidth;//找到最小高度列int minColNum = getMinColNumber();left = minColNum*(mHorozontalSpace + childWidth);top = mTop[minColNum];right = left+childWidth;bottom = top + childHeight;viewChild.layout(left,top,right,bottom);//记录每一行的高mTop[minColNum] += childHeight + mVerticalSpace;}}private void clearTop() {for (int i = 0; i < mTop.length; i++) {mTop[i] = 0;}}public int getMaxHeight() {for (int i = 0; i < mTop.length; i++) {if (mTop[i] > maxHeight){maxHeight = mTop[i];}}return maxHeight;}public int getMinColNumber() {for (int i = 0; i < mTop.length; i++) {if (mTop[minColNumber] > mTop[i]){minColNumber = i;}}return minColNumber;}
}

该控件对应的一些属性值。

<?xml version="1.0" encoding="utf-8"?>
<resources><declare-styleable name="WaterFallLayout"><attr name="mColNumber" format="integer"/><attr name="mHorozontalSpace" format="dimension"/><attr name="mVerticalSpace" format="dimension"/></declare-styleable>
</resources>

还有一个方法类,将dp转px。

package com.example.administrator.myapplication.flow;import android.content.Context;/*** Created by ShuWen on 2017/6/9.*/public class DensityUtil {/*** 根据手机的分辨率从 dp 的单位 转成为 px(像素)** @param context* @param dpValue* @return* @date   2015年10月28日*/public static int dip2px(Context context, float dpValue) {final float scale = context.getResources().getDisplayMetrics().density;return (int) (dpValue * scale + 0.5f);}/*** 根据手机的分辨率从 px(像素) 的单位 转成为 dp** @param context* @param pxValue* @return* @date   2015年10月28日*/public static int px2dip(Context context, float pxValue) {final float scale = context.getResources().getDisplayMetrics().density;return (int) (pxValue / scale + 0.5f);}
}

然后看看MainActivity

package com.example.administrator.myapplication;import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.ImageView;import com.example.administrator.myapplication.flow.WaterFallLayout;import java.util.Random;public class MainActivity extends AppCompatActivity {WaterFallLayout waterfall;private static int IMG_COUNT = 5;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);waterfall = (WaterFallLayout) findViewById(R.id.waterfall);for (int i = 0; i < 20; i++) {ImageView imageView = new ImageView(this);imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));Random random = new Random();Integer num = Math.abs(random.nextInt());if (num % IMG_COUNT == 0) {imageView.setImageResource(R.drawable.a0);} else if (num % IMG_COUNT == 1) {imageView.setImageResource(R.drawable.a1);} else if (num % IMG_COUNT == 2) {imageView.setImageResource(R.drawable.a2);} else if (num % IMG_COUNT == 3) {imageView.setImageResource(R.drawable.a3);} else if (num % IMG_COUNT == 4) {imageView.setImageResource(R.drawable.a4);}else if (num % IMG_COUNT == 5) {imageView.setImageResource(R.drawable.a5);}waterfall.addView(imageView);}}}

看看布局。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"xmlns:app="http://schemas.android.com/apk/res-auto"tools:context="com.example.administrator.myapplication.MainActivity"><!--<com.airbnb.lottie.LottieAnimationView--><!--android:id="@+id/animation_view"--><!--android:layout_width="wrap_content"--><!--android:layout_height="wrap_content"--><!--app:lottie_fileName="pin.json"--><!--android:layout_centerInParent="true"--><!--app:lottie_loop="true"--><!--app:lottie_autoPlay="true" />--><ScrollView
        android:layout_width="match_parent"android:layout_height="match_parent"><com.example.administrator.myapplication.flow.WaterFallLayout
            android:id="@+id/waterfall"android:layout_width="wrap_content"android:layout_height="wrap_content"app:mColNumber="3"app:mHorozontalSpace="5dp"app:mVerticalSpace="5dp"></com.example.administrator.myapplication.flow.WaterFallLayout></ScrollView></RelativeLayout>

简单粗暴,这个例子有利于理解ViewGroup的一些计算逻辑,为其他复杂自定义控件打下基础。

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



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

相关文章

Flutter实现文字镂空效果的详细步骤

《Flutter实现文字镂空效果的详细步骤》:本文主要介绍如何使用Flutter实现文字镂空效果,包括创建基础应用结构、实现自定义绘制器、构建UI界面以及实现颜色选择按钮等步骤,并详细解析了混合模... 目录引言实现原理开始实现步骤1:创建基础应用结构步骤2:创建主屏幕步骤3:实现自定义绘制器步骤4:构建U

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义