【Android -- UI 开发】Recyclerview 的通用分隔线

2023-12-29 22:30

本文主要是介绍【Android -- UI 开发】Recyclerview 的通用分隔线,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

不断学习,做更好的自己!💪

视频号CSDN简书
欢迎打开微信,关注我的视频号:KevinDev点我点我

简介

ItemDecorationRecyclerView 的一个抽象静态内部类,负责装饰 Item 视图,例如添加间距、高亮或者分组边界等。

LinearLayoutManager 添加分割线

1. 效果图
在这里插入图片描述

2. 源码

public class DividerItemDecoration extends RecyclerView.ItemDecoration{private Context mContext;private Drawable mDivider;private int mOrientation;public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;//我们通过获取系统属性中的listDivider来添加,在系统中的AppTheme中设置public static final int[] ATRRS  = new int[]{android.R.attr.listDivider};public DividerItemDecoration(Context context, int orientation) {this.mContext = context;final TypedArray ta = context.obtainStyledAttributes(ATRRS);this.mDivider = ta.getDrawable(0);ta.recycle();setOrientation(orientation);}//设置屏幕的方向public void setOrientation(int orientation){if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST){throw new IllegalArgumentException("invalid orientation");}mOrientation = orientation;}@Overridepublic void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {if (mOrientation == HORIZONTAL_LIST){drawVerticalLine(c, parent, state);}else {drawHorizontalLine(c, parent, state);}}//画横线, 这里的parent其实是显示在屏幕显示的这部分public void drawHorizontalLine(Canvas c, RecyclerView parent, RecyclerView.State state){int left = parent.getPaddingLeft();int right = parent.getWidth() - parent.getPaddingRight();final int childCount = parent.getChildCount();for (int i = 0; i < childCount; i++){final View child = parent.getChildAt(i);//获得child的布局信息final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)child.getLayoutParams();final int top = child.getBottom() + params.bottomMargin;final int bottom = top + mDivider.getIntrinsicHeight();mDivider.setBounds(left, top, right, bottom);mDivider.draw(c);//Log.d("wnw", left + " " + top + " "+right+"   "+bottom+" "+i);}}//画竖线public void drawVerticalLine(Canvas c, RecyclerView parent, RecyclerView.State state){int top = parent.getPaddingTop();int bottom = parent.getHeight() - parent.getPaddingBottom();final int childCount = parent.getChildCount();for (int i = 0; i < childCount; i++){final View child = parent.getChildAt(i);//获得child的布局信息final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)child.getLayoutParams();final int left = child.getRight() + params.rightMargin;final int right = left + mDivider.getIntrinsicWidth();mDivider.setBounds(left, top, right, bottom);mDivider.draw(c);}}//由于Divider也有长宽高,每一个Item需要向下或者向右偏移@Overridepublic void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {if(mOrientation == HORIZONTAL_LIST){//画横线,就是往下偏移一个分割线的高度outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());}else {//画竖线,就是往右偏移一个分割线的宽度outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);}}
}

3. 使用方法

		LinearLayoutManager manager = new LinearLayoutManager(this);mRecyclerView.setLayoutManager(manager);mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));mRecyclerView.setAdapter(mAdapter);

GridLayoutManager 添加分割线

1. 效果图
在这里插入图片描述

2. 源码

public class GridDividerItemDecoration extends RecyclerView.ItemDecoration {private Context mContext;private int mFirstAndLastColumnW;          //您所需指定的间隔宽度,主要为第一列和最后一列与父控件的间隔;行间距,列间距将动态分配private int mFirstRowTopMargin = 0; //第一行顶部是否需要间隔private int mLastRowBottomMargin = 0;private int mSpanCount = 0;private int mScreenW = 0;private int mItemDistance;/*** @param firstAndLastColumnW 间隔宽度* @param firstRowTopMargin   第一行顶部是否需要间隔*/public GridDividerItemDecoration(Context context, int firstAndLastColumnW, int firstRowTopMargin, int lastRowBottomMargin) {mContext = context;mFirstAndLastColumnW = firstAndLastColumnW;mFirstRowTopMargin = firstRowTopMargin;mLastRowBottomMargin = lastRowBottomMargin;}public void setFirstRowTopMargin(int firstRowTopMargin) {mFirstRowTopMargin = firstRowTopMargin;}public void setLastRowBottomMargin(int lastRowBottomMargin) {mLastRowBottomMargin = lastRowBottomMargin;}public void setItemDistance(int itemDistance) {mItemDistance = itemDistance;}@Overridepublic void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {super.getItemOffsets(outRect, view, parent, state);int top = 0;int left;int right;int bottom;int itemPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();mSpanCount = getSpanCount(parent);int childCount = parent.getAdapter().getItemCount();// 屏幕宽度-View的宽度*spanCount 得到屏幕剩余空间int maxDividerWidth = getMaxDividerWidth(view);int spaceWidth = mFirstAndLastColumnW;//首尾两列与父布局之间的间隔// 除去首尾两列,item与item之间的距离int eachItemWidth = maxDividerWidth / mSpanCount;int dividerItemWidth = (maxDividerWidth - 2 * spaceWidth) / (mSpanCount - 1);//item与item之间的距离left = itemPosition % mSpanCount * (dividerItemWidth - eachItemWidth) + spaceWidth;right = eachItemWidth - left;bottom = dividerItemWidth;// 首行if (mFirstRowTopMargin > 0 && isFirstRow(parent, itemPosition, mSpanCount, childCount)) {top = mFirstRowTopMargin;}//最后一行if (isLastRow(parent, itemPosition, mSpanCount, childCount)) {if (mLastRowBottomMargin < 0) {bottom = 0;} else {bottom = mLastRowBottomMargin;}}outRect.set(left, top, right, bottom);}/*** 获取Item View的大小,若无则自动分配空间* 并根据 屏ge幕宽度-View的宽度*spanCount 得到屏幕剩余空间** @param view* @return*/private int getMaxDividerWidth(View view) {int itemWidth = view.getLayoutParams().width;int itemHeight = view.getLayoutParams().height;int screenWidth = getScreenWidth();int maxDividerWidth = screenWidth - itemWidth * mSpanCount;if (itemHeight < 0 || itemWidth < 0 || maxDividerWidth <= (mSpanCount - 1) * mFirstAndLastColumnW) {view.getLayoutParams().width = getAttachCloumnWidth();view.getLayoutParams().height = getAttachCloumnWidth();maxDividerWidth = screenWidth - view.getLayoutParams().width * mSpanCount;}return maxDividerWidth;}private int getScreenWidth() {if (mScreenW > 0) {return mScreenW;}mScreenW = mContext.getResources().getDisplayMetrics().widthPixels > mContext.getResources().getDisplayMetrics().heightPixels? mContext.getResources().getDisplayMetrics().heightPixels : mContext.getResources().getDisplayMetrics().widthPixels;return mScreenW;}/*** 根据屏幕宽度和item数量分配 item View的width和height** @return*/private int getAttachCloumnWidth() {int itemWidth = 0;int spaceWidth = 0;try {int width = getScreenWidth();spaceWidth = 2 * mFirstAndLastColumnW;itemWidth = (width - spaceWidth) / mSpanCount - 40;} catch (Exception e) {e.printStackTrace();}return itemWidth;}/*** 判读是否是第一列** @param parent* @param pos* @param spanCount* @return*/private boolean isFirstColumn(RecyclerView parent, int pos, int spanCount) {RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();if (layoutManager instanceof GridLayoutManager) {if (pos % spanCount == 0) {return true;}} else if (layoutManager instanceof StaggeredGridLayoutManager) {int orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();if (orientation == StaggeredGridLayoutManager.VERTICAL) {if (pos % spanCount == 0) {// 第一列return true;}} else {}}return false;}/*** 判断是否是最后一列** @param parent* @param pos* @param spanCount* @return*/private boolean isLastColumn(RecyclerView parent, int pos, int spanCount) {RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();if (layoutManager instanceof GridLayoutManager) {if ((pos + 1) % spanCount == 0) {// 如果是最后一列,则不需要绘制右边return true;}} else if (layoutManager instanceof StaggeredGridLayoutManager) {int orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();if (orientation == StaggeredGridLayoutManager.VERTICAL) {if ((pos + 1) % spanCount == 0) {// 最后一列return true;}} else {}}return false;}/*** 判读是否是最后一行** @param parent* @param pos* @param spanCount* @param childCount* @return*/private boolean isLastRow(RecyclerView parent, int pos, int spanCount, int childCount) {RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();if (layoutManager instanceof GridLayoutManager) {int lines = childCount % spanCount == 0 ? childCount / spanCount : childCount / spanCount + 1;return lines == pos / spanCount + 1;}return false;}/*** 判断是否是第一行** @param parent* @param pos* @param spanCount* @param childCount* @return*/private boolean isFirstRow(RecyclerView parent, int pos, int spanCount, int childCount) {RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();if (layoutManager instanceof GridLayoutManager) {if ((pos / spanCount + 1) == 1) {return true;} else {return false;}}return false;}/*** 获取列数** @param parent* @return*/private int getSpanCount(RecyclerView parent) {int spanCount = -1;RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();if (layoutManager instanceof GridLayoutManager) {spanCount = ((GridLayoutManager) layoutManager).getSpanCount();} else if (layoutManager instanceof StaggeredGridLayoutManager) {spanCount = ((StaggeredGridLayoutManager) layoutManager).getSpanCount();}return spanCount;}
}

3. 使用方法

		int firstAndLastColumnW = DensityUtil.dip2px(this, 20);int firstRowTopMargin = DensityUtil.dip2px(this, 20);GridDividerItemDecoration gridDividerItemDecoration =new GridDividerItemDecoration(this, firstAndLastColumnW, firstRowTopMargin, firstRowTopMargin);gridDividerItemDecoration.setFirstRowTopMargin(firstRowTopMargin);gridDividerItemDecoration.setLastRowBottomMargin(firstRowTopMargin);mRecyclerView.addItemDecoration(gridDividerItemDecoration);GridLayoutManager layoutManager = new GridLayoutManager(this, 3);mRecyclerView.setLayoutManager(layoutManager);mRecyclerView.setAdapter(mAdapter);

这篇关于【Android -- UI 开发】Recyclerview 的通用分隔线的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Android开发中gradle下载缓慢的问题级解决方法

《Android开发中gradle下载缓慢的问题级解决方法》本文介绍了解决Android开发中Gradle下载缓慢问题的几种方法,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、网络环境优化二、Gradle版本与配置优化三、其他优化措施针对android开发中Gradle下载缓慢的问

使用Go语言开发一个命令行文件管理工具

《使用Go语言开发一个命令行文件管理工具》这篇文章主要为大家详细介绍了如何使用Go语言开发一款命令行文件管理工具,支持批量重命名,删除,创建,移动文件,需要的小伙伴可以了解下... 目录一、工具功能一览二、核心代码解析1. 主程序结构2. 批量重命名3. 批量删除4. 创建文件/目录5. 批量移动三、如何安

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

Android里面的Service种类以及启动方式

《Android里面的Service种类以及启动方式》Android中的Service分为前台服务和后台服务,前台服务需要亮身份牌并显示通知,后台服务则有启动方式选择,包括startService和b... 目录一句话总结:一、Service 的两种类型:1. 前台服务(必须亮身份牌)2. 后台服务(偷偷干

基于Python开发PPTX压缩工具

《基于Python开发PPTX压缩工具》在日常办公中,PPT文件往往因为图片过大而导致文件体积过大,不便于传输和存储,所以本文将使用Python开发一个PPTX压缩工具,需要的可以了解下... 目录引言全部代码环境准备代码结构代码实现运行结果引言在日常办公中,PPT文件往往因为图片过大而导致文件体积过大,

Android kotlin语言实现删除文件的解决方案

《Androidkotlin语言实现删除文件的解决方案》:本文主要介绍Androidkotlin语言实现删除文件的解决方案,在项目开发过程中,尤其是需要跨平台协作的项目,那么删除用户指定的文件的... 目录一、前言二、适用环境三、模板内容1.权限申请2.Activity中的模板一、前言在项目开发过程中,尤

使用DeepSeek API 结合VSCode提升开发效率

《使用DeepSeekAPI结合VSCode提升开发效率》:本文主要介绍DeepSeekAPI与VisualStudioCode(VSCode)结合使用,以提升软件开发效率,具有一定的参考价值... 目录引言准备工作安装必要的 VSCode 扩展配置 DeepSeek API1. 创建 API 请求文件2.

Vue项目中Element UI组件未注册的问题原因及解决方法

《Vue项目中ElementUI组件未注册的问题原因及解决方法》在Vue项目中使用ElementUI组件库时,开发者可能会遇到一些常见问题,例如组件未正确注册导致的警告或错误,本文将详细探讨这些问题... 目录引言一、问题背景1.1 错误信息分析1.2 问题原因二、解决方法2.1 全局引入 Element

基于Python开发电脑定时关机工具

《基于Python开发电脑定时关机工具》这篇文章主要为大家详细介绍了如何基于Python开发一个电脑定时关机工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 简介2. 运行效果3. 相关源码1. 简介这个程序就像一个“忠实的管家”,帮你按时关掉电脑,而且全程不需要你多做

Java中的Opencv简介与开发环境部署方法

《Java中的Opencv简介与开发环境部署方法》OpenCV是一个开源的计算机视觉和图像处理库,提供了丰富的图像处理算法和工具,它支持多种图像处理和计算机视觉算法,可以用于物体识别与跟踪、图像分割与... 目录1.Opencv简介Opencv的应用2.Java使用OpenCV进行图像操作opencv安装j