当前位置: 首页 > news >正文

安卓LayoutParams浅析

目录

  • 前言
  • 一、使用 LayoutParams 设置宽高
  • 二、不设置 LayoutParams
    • 2.1 TextView 的 LayoutParams
    • 2.2 LinearLayout 的 LayoutParams
  • 三、getLayoutParams 的使用
  • 四、setLayoutParams 的作用
  • 五、使用 setWidth/setHeight 设置宽高


前言

先来看一个简单的布局,先用 xml 写

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#00F5FF"android:gravity="center"android:orientation="vertical"><TextViewandroid:layout_width="160dp"android:layout_height="160dp"android:background="#FFFACD"android:text="12345678" /></LinearLayout>

效果也很简单:
在这里插入图片描述

如果想要代码动态写出上面的布局,就需要使用 LayoutParams 这个关键类了,
LayoutParams 是 ViewGroup 的一个内部类,这是一个基类,例如 FrameLayout、LinearLayout 等等,内部都有自己的 LayoutParams。

一、使用 LayoutParams 设置宽高

LayoutParams 的作用是: 子控件告诉父控件,自己要如何布局。

代码实现:

public class LayoutFragment extends Fragment {@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {LinearLayout ll = new LinearLayout(getContext());
//11的父容器是MainActivity中的FrameLayoutll.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));ll.setGravity(Gravity.CENTER);ll.setBackgroundColor(Color.BLUE);TextView tv = new TextView(getContext());
//tv的父容器是LinearLayoutLinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(160, 160);tv.setLayoutParams(layoutParams);//tv.setBackgroundColor(Color.RED);tv.setText("123145678");ll.addView(tv);// creturn ll;}
}

我们对 LinearLayout 和 TextView 的 LayoutParams 都进行了设置,效果图和上面 xml的是一模一样的。
ll.setLayoutParams 设置的是其父布局 FrameLayout 的 LayoutParams,并且告诉父布局,宽高设置为 MATCH_PARENT。
tv.setLayoutParams 设置的也是其父布局 LinearLayout 的 LayoutParams,并且告诉父布局,宽高设置为 160dp。
上面 ①、 ② 两行代码可以简化为一行,替换为 addView(View child, LayoutParamsparams) 这个重载方法,在添加到父布局时,设置 LayoutParams,通知父布局如何摆放自己。
ll.addView(tv, layoutParams);// 子布局添加到父布局


二、不设置 LayoutParams

public class LayoutFragment extends Fragment {@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {LinearLayout ll = new LinearLayout(getContext());ll.setGravity(Gravity.CENTER);ll.setBackgroundColor(Color.BLUE);TextView tv = new TextView(getContext());
//tv的父容器是LinearLayouttv.setBackgroundColor(Color.RED);tv.setText("123145678");ll.addView(tv);// creturn ll;}
}
public class MainActivity extends AppCompatActivity {private static final String TAG = "henry-----";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);FragmentManager fragmentManager = getSupportFragmentManager();FragmentTransaction transaction = fragmentManager.beginTransaction();LayoutFragment fragment = new LayoutFragment();transaction.add(R.id.test, fragment);transaction.commit();}}

效果如下:
在这里插入图片描述
发现在对 LinearLayout 和 TextView 的 都不设置 LayoutParams 的情况下,LinearLayout 使用 MATCH_PARENT,而 TextView 使用 WRAP_CONTENT,至于为什么,要分析一下源码

2.1 TextView 的 LayoutParams

进入 addView 看一下,不存在 LayoutParams 时,会调用generateDefaultLayoutParams() 进行创建。

    public void addView(View child, int index) {if (child == null) {throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");}LayoutParams params = child.getLayoutParams();if (params == null) {params = generateDefaultLayoutParams();if (params == null) {throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null  ");}}addView(child, index, params);}

找到 LinearLayout 中 generateDefaultLayoutParams(),注意不是 ViewGroup 中的

    protected LayoutParams generateDefaultLayoutParams() {if (mOrientation == HORIZONTAL) {return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);} else if (mOrientation == VERTICAL) {return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);}return null;}

显而易见,由于我们没有指定方向, mOrientation 默认为 0,也就是 HORIZONTAL,所以 TextView 设置为
WRAP_CONTENT,为了证实猜想,我们设置 LinearLayout 的方向为 VERTICAL。

        ll.setOrientation(LinearLayout.VERTICAL);

效果跟代码看到的一样,宽度为 MATCH_PARENT,高度为WRAP_CONTENT:
在这里插入图片描述

2.2 LinearLayout 的 LayoutParams

和上面 TextView 一样,这个要进入 FrameLayout 中查看 generateDefaultLayoutParams()。

    protected LayoutParams generateDefaultLayoutParams() {return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);}

所以,在 FrameLayout 中的 LinearLayout 的宽高就是 MATCH_PARENT。


三、getLayoutParams 的使用

在不使用代码动态布局的情况下,大都是先通过 getLayoutParams() 获取LayoutParams ,然后进行赋值,最后通过 setLayoutParams()设回控件,值得注意的是,获取 LayoutParams 务必要强转为父控件的类型,才会有该父控件特有的方法。

public class LayoutFragment extends Fragment {@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {LinearLayout ll = new LinearLayout(getContext());
// ll 的父容器是 MainActivity 中的 FrameLayoutFrameLayout.LayoutParams fl_params = (FrameLayout.LayoutParams)ll.getLayoutParams();// ①fl_params.width = ViewGroup.LayoutParams.MATCH_PARENT;fl_params.height = ViewGroup.LayoutParams.MATCH_PARENT;ll.setLayoutParams(fl_params);ll.setGravity(Gravity.CENTER);ll.setBackgroundResource(android.R.color.holo_blue_bright);TextView tv = new TextView(getContext());
// tv 的父容器是 LinearLayoutLinearLayout.LayoutParams ll_params = (LinearLayout.LayoutParams)tv.getLayoutParams();// ②ll_params.width = 160;ll_params.height = 160;tv.setLayoutParams(ll_params);tv.setBackgroundResource(android.R.color.holo_red_dark);tv.setText("12345678");ll.addView(tv);return ll;}
}

运行报错:
在这里插入图片描述

上面代码是有问题的, ①、 ②处都会返回 null,导致空指针。
①处:此时还没有将 LinearLayout 作为返回值返回,也就没有添加到布局中,自然不存
在 LayoutParams。
②处:此时还没有将 TextView 添加到 LinearLayout 中,也不存在 LayoutParams。
下面才是正确的示例:

public class LayoutFragment extends Fragment {@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {LinearLayout ll = new LinearLayout(getContext());
// ll 的父容器是 MainActivity 中的 FrameLayoutll.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));ll.setGravity(Gravity.CENTER);// 子控件居中ll.setBackgroundResource(android.R.color.holo_blue_bright);TextView tv = new TextView(getContext());ll.addView(tv);// 添加到父控件,此时会构造一个 LayoutParams 出来。LinearLayout.LayoutParams ll_params = (LinearLayout.LayoutParams)tv.getLayoutParams();ll_params.width = 160;ll_params.height = 160;tv.setLayoutParams(ll_params);tv.setBackgroundResource(android.R.color.holo_red_dark);tv.setText("12345678");return ll;}
}

四、setLayoutParams 的作用

这里抛出一个问题:
上面代码中 getLayoutParams() 得到了 LayoutParams 的引用 ll_params,直接对width 和 height 属性赋值,那么 setLayoutParams() 是不是不需要调用了?
这就需要看看 setLayoutParams() 里面干了什么

    public void setLayoutParams(ViewGroup.LayoutParams params) {if (params == null) {throw new NullPointerException("Layout parameters cannot be null");}mLayoutParams = params;resolveLayoutParams();if (mParent instanceof ViewGroup) {((ViewGroup) mParent).onSetLayoutParams(this, params);}requestLayout();}

关键的最后一行 requestLayout() ,这个方法简单来说,就是重新执行 onMeasure() 和onLayout(),而 onDraw() 需要适情况而定,这里就不具体展开说了。
现在就可以回答上面的问题了,在上面 onCreateView() 中的 setLayoutParams() 确实是多余的,因为在 onCreateView() 之后才会进行 View 的绘制。
当然这并不是说 setLayoutParams() 没有用,在自定义控件中,往往需要在 View 绘制后修改 LayoutParams 的值,那么这种场景下,如果不调用 setLayoutParams() 就会出现设置不生效的问题。
总结:

  • 在 LayoutParams 赋值后,如果确定还没有完成 View 的绘制,可以省略setLayoutParams() ,在后面绘制期间,会取到前面的赋值,并使之生效。
  • 如果已经完成了 View 的绘制,那么必须要调用setLayoutParams() ,重新进行绘制。
  • 不确定的情况下就setLayoutParams() ,反正不会出问题。

五、使用 setWidth/setHeight 设置宽高

在设置控件宽高时,有些人为了方便,没有使用 LayoutParams ,直接通过 set 方法设置,
但这种方式并不靠谱!

对 TextView 和 Button 分别设置宽高为 160px

public class LayoutFragment extends Fragment {@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {LinearLayout ll = new LinearLayout(getContext());
// ll 的父容器是 MainActivity 中的 FrameLayoutll.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));ll.setGravity(Gravity.CENTER);// 子控件居中ll.setBackgroundResource(android.R.color.holo_blue_bright);TextView tv = new TextView(getContext());tv.setWidth(160);tv.setHeight(160);tv.setBackgroundResource(android.R.color.holo_red_dark);tv.setText("12345678");ll.addView(tv);Button bt = new Button(getContext());bt.setWidth(160);bt.setHeight(160);bt.setBackgroundResource(android.R.color.holo_green_dark);bt.setText("12345678");ll.addView(bt);return ll;}
}

TextView 设置宽高成功, Button 只在高度上生效,效果如下:

在这里插入图片描述

可以打印下控件宽高看下结果:
在这里插入图片描述

Button 也是继承 TextView,为什么会出现设置失效?进入 setWidth 方法,看到在这里只是设置了控件的最大值和最小值:

    public void setWidth(int pixels) {mMaxWidth = mMinWidth = pixels;mMaxWidthMode = mMinWidthMode = PIXELS;requestLayout();invalidate();}

LayoutParams 设置的宽高才是真正的宽高:

在这里插入图片描述

再看下 onMeasure 中,这里面设置 width 时,有很多类似下面判断:
在这里插入图片描述

所以 setWidth()/setHeight 只代表想设置的宽高,并不是实际设定值。这就很好理解,
当 set 的值大于 Button 最小宽度/高度时生效,在小于 Button 最小宽度/高度时,不能起到作用。


相关文章:

安卓LayoutParams浅析

目录 前言一、使用 LayoutParams 设置宽高二、不设置 LayoutParams2.1 TextView 的 LayoutParams2.2 LinearLayout 的 LayoutParams 三、getLayoutParams 的使用四、setLayoutParams 的作用五、使用 setWidth/setHeight 设置宽高 前言 先来看一个简单的布局&#xff0c;先用 x…...

UltralSO制作启动盘时报错:磁盘/映像容量太小解决办法

UltralSO制作启动盘时报错&#xff1a;磁盘/映像容量太小解决办法 发现网上随便下载的UltralSO制作启动盘时报错&#xff1a;磁盘/映像容量太小&#xff0c;导致制作启动盘出错 解决方案&#xff1a; 去这个地址下载&#xff1a;https://cn.ultraiso.net/xiazai.html 下载正版…...

2024-05-09四月初二周四

2024-05-09四月初二周四 06:40-23:00 深兰Ai第五期 Part1:课时258&#xff1a;00:00:00 12:30-13:00 午饭烧水&#xff1a; 13:30-23:00 机器学习 19:00-20:00 晚饭&#xff1a; 20:00-23:00 coding 2.5 特征降维 unending 23:00-06:30 烧水资料下载...

【微服务】springcloud整合dubbo3使用nacos作为注册中心

目录 一、前言 二、springboot版本升级带来的问题 2.1 springboot为什么需要升级版本...

php中常用的数据类型汇总

在 PHP 中&#xff0c;常用的数据类型主要有以下几种&#xff1a; 标量类型&#xff08;Scalar Types&#xff09; integer&#xff08;整型&#xff09;&#xff1a;用于存储整数&#xff0c;可以是正数或负数。float&#xff08;浮点型/双精度型&#xff09;&#xff1a;用于…...

【源码阅读】Golang中的go-sql-driver库源码探究

文章目录 前言一、go-sql-driver/mysql1、驱动注册&#xff1a;sql.Register2、驱动实现&#xff1a;MysqlDriver3、RegisterDialContext 二、总结 前言 在上篇文章中我们知道&#xff0c;database/sql只是提供了驱动相关的接口&#xff0c;并没有相关的具体实现&#xff0c;具…...

2024-05-08 postgres-火山模型-执行-记录

摘要: 2024-05-08 postgres-火山模型-执行-记录 上下文: 2024-05-08 postgres-调试及分析-记录-CSDN博客 火山模型: 数据流是在查询树上&#xff0c;自上而下进行拉取&#xff0c;由上而下的调用。树本身就表明了数据的流动。每次执行一个元组&#xff0c;也就类似于迭代器的…...

QT5带UI的常用控件

目录 新建工程&#xff0c;Qmainwindow带UI UI设计器 常用控件区 Buttons 按钮 containers 容器 控件属性区域 对象监视区 布局工具区 信号与槽区 简单例子1 放置一个按钮控件&#xff0c;改文本为发送&#xff0c;该按键为Button1&#xff1b; 按钮关联信号和…...

识货小程序逆向

声明 本文章中所有内容仅供学习交流使用&#xff0c;不用于其他任何目的&#xff0c;抓包内容、敏感网址、数据接口等均已做脱敏处理&#xff0c;严禁用于商业用途和非法用途&#xff0c;否则由此产生的一切后果均与作者无关&#xff01;wx a15018601872&#xff0c;x30184483x…...

【OceanBase 系列】—— OceanBase v4.3 特性解读:查询性能提升之利器列存储引擎

原文链接&#xff1a;OceanBase 社区 对于分析类查询&#xff0c;列存可以极大地提升查询性能&#xff0c;也是 OceanBase 做好 HTAP 和 OLAP 的一项不可缺少的特性。本文介绍 OceanBase 列存的实现特色。 OceanBase从诞生起就一直坚持LSM-Tree架构&#xff0c;不断打磨功能支…...

【Java开发的我出书啦,各位同仁快过来围观】!!!

文章目录 &#x1f50a;博主介绍&#x1f964;本文内容出书的目的出书的过程书籍的内容 &#x1f4e5;博主的话 &#x1f50a;博主介绍 文章目录 &#x1f50a;博主介绍&#x1f964;本文内容出书的目的出书的过程书籍的内容 &#x1f4e5;博主的话 &#x1f33e;阅读前&#x…...

AI预测福彩3D第10套算法实战化赚米验证第1弹2024年5月5日第1次测试

从今天开始&#xff0c;准备启用第10套算法&#xff0c;来验证下本算法的可行性。因为本算法通过近三十期的内测&#xff08;内测版没有公开预测结果&#xff09;&#xff0c;发现本算法的预测结果优于其他所有算法的效果。彩票预测只有实战才能检验是否有效&#xff0c;只有真…...

leetcode 2944.购买水果需要的最小金币

思路&#xff1a;dp 这道题一开始想的时候并不会&#xff0c;但是看到了有些水果可以买也可以不买&#xff0c;所以就想到了选择与不选择的思路。 对于每一个水果&#xff0c;我们都有买和不买的选择&#xff0c;但是我们的第一个水果是一定要买的。然后再往后推导。 用dp[]…...

算法人生(14):从“探索平衡策略”看“生活工作的平衡之道”

在强化学习中&#xff0c;有一种策略叫“探索平衡策略Exploration-Exploitation Trade-off&#xff09;”&#xff0c;这种策略的核心是在探索未知领域&#xff08;以获取更多信息&#xff09;和利用已知信息&#xff08;来最大化即时回报&#xff09;之间寻求平衡&#xff0c;…...

如何使用Tushare+ Backtrader进行股票量化策略回测

数量技术宅团队在CSDN学院推出了量化投资系列课程 欢迎有兴趣系统学习量化投资的同学&#xff0c;点击下方链接报名&#xff1a; 量化投资速成营&#xff08;入门课程&#xff09; Python股票量化投资 Python期货量化投资 Python数字货币量化投资 C语言CTP期货交易系统开…...

Guid转换为字符串

在理想情况下&#xff0c;任何计算机和计算机集群都不会生成两个相同的GUID。GUID 的总数达到了2128&#xff08;3.41038&#xff09;个&#xff0c;所以随机生成两个相同GUID的可能性非常小&#xff0c;但并不为0。GUID一词有时也专指微软对UUID标准的实现。 (1). GUID&#…...

OpenAI的搜索引擎要来了!

最近的报道和业界泄露信息显示&#xff0c;OpenAI正秘密研发一款新的搜索引擎&#xff0c;可能叫SearchGPT或Sonic&#xff0c;目标是挑战Google的搜索霸权。预计这款搜索引擎可能在5月9日即将到来的活动中正式亮相。 SearchGPT的蛛丝马迹 尽管OpenAI对SearchGPT尚未表态&…...

PaddlePaddle与OpenMMLab

产品全景_飞桨产品-飞桨PaddlePaddle OpenMMLab算法应用平台...

HBuilderX uniapp+vue3+vite axios封装

uniapp 封装axios 注&#xff1a;axios必须低于0.26.0&#xff0c;重中之重 重点&#xff1a;封装axios的适配器adapter 1.安装axios npm install axios0.26.0创建api文件夹 2.新建adapter.js文件 import settle from "axios/lib/core/settle" import buildURL…...

【网络安全产品】---应用防火墙(WAF)

what Web应用防火墙&#xff08;Web Application Firewall) WAF可对网站或者App的业务流量进行恶意特征识别及防护&#xff0c;在对流量清洗和过滤后&#xff0c;将正常、安全的流量返回给服务器&#xff0c;避免网站服务器被恶意入侵导致性能异常等问题&#xff0c;从而保障…...

手游刚开服就被攻击怎么办?如何防御DDoS?

开服初期是手游最脆弱的阶段&#xff0c;极易成为DDoS攻击的目标。一旦遭遇攻击&#xff0c;可能导致服务器瘫痪、玩家流失&#xff0c;甚至造成巨大经济损失。本文为开发者提供一套简洁有效的应急与防御方案&#xff0c;帮助快速应对并构建长期防护体系。 一、遭遇攻击的紧急应…...

基于FPGA的PID算法学习———实现PID比例控制算法

基于FPGA的PID算法学习 前言一、PID算法分析二、PID仿真分析1. PID代码2.PI代码3.P代码4.顶层5.测试文件6.仿真波形 总结 前言 学习内容&#xff1a;参考网站&#xff1a; PID算法控制 PID即&#xff1a;Proportional&#xff08;比例&#xff09;、Integral&#xff08;积分&…...

FFmpeg 低延迟同屏方案

引言 在实时互动需求激增的当下&#xff0c;无论是在线教育中的师生同屏演示、远程办公的屏幕共享协作&#xff0c;还是游戏直播的画面实时传输&#xff0c;低延迟同屏已成为保障用户体验的核心指标。FFmpeg 作为一款功能强大的多媒体框架&#xff0c;凭借其灵活的编解码、数据…...

【第二十一章 SDIO接口(SDIO)】

第二十一章 SDIO接口 目录 第二十一章 SDIO接口(SDIO) 1 SDIO 主要功能 2 SDIO 总线拓扑 3 SDIO 功能描述 3.1 SDIO 适配器 3.2 SDIOAHB 接口 4 卡功能描述 4.1 卡识别模式 4.2 卡复位 4.3 操作电压范围确认 4.4 卡识别过程 4.5 写数据块 4.6 读数据块 4.7 数据流…...

Cilium动手实验室: 精通之旅---20.Isovalent Enterprise for Cilium: Zero Trust Visibility

Cilium动手实验室: 精通之旅---20.Isovalent Enterprise for Cilium: Zero Trust Visibility 1. 实验室环境1.1 实验室环境1.2 小测试 2. The Endor System2.1 部署应用2.2 检查现有策略 3. Cilium 策略实体3.1 创建 allow-all 网络策略3.2 在 Hubble CLI 中验证网络策略源3.3 …...

屋顶变身“发电站” ,中天合创屋面分布式光伏发电项目顺利并网!

5月28日&#xff0c;中天合创屋面分布式光伏发电项目顺利并网发电&#xff0c;该项目位于内蒙古自治区鄂尔多斯市乌审旗&#xff0c;项目利用中天合创聚乙烯、聚丙烯仓库屋面作为场地建设光伏电站&#xff0c;总装机容量为9.96MWp。 项目投运后&#xff0c;每年可节约标煤3670…...

spring:实例工厂方法获取bean

spring处理使用静态工厂方法获取bean实例&#xff0c;也可以通过实例工厂方法获取bean实例。 实例工厂方法步骤如下&#xff1a; 定义实例工厂类&#xff08;Java代码&#xff09;&#xff0c;定义实例工厂&#xff08;xml&#xff09;&#xff0c;定义调用实例工厂&#xff…...

ETLCloud可能遇到的问题有哪些?常见坑位解析

数据集成平台ETLCloud&#xff0c;主要用于支持数据的抽取&#xff08;Extract&#xff09;、转换&#xff08;Transform&#xff09;和加载&#xff08;Load&#xff09;过程。提供了一个简洁直观的界面&#xff0c;以便用户可以在不同的数据源之间轻松地进行数据迁移和转换。…...

Maven 概述、安装、配置、仓库、私服详解

目录 1、Maven 概述 1.1 Maven 的定义 1.2 Maven 解决的问题 1.3 Maven 的核心特性与优势 2、Maven 安装 2.1 下载 Maven 2.2 安装配置 Maven 2.3 测试安装 2.4 修改 Maven 本地仓库的默认路径 3、Maven 配置 3.1 配置本地仓库 3.2 配置 JDK 3.3 IDEA 配置本地 Ma…...

Reasoning over Uncertain Text by Generative Large Language Models

https://ojs.aaai.org/index.php/AAAI/article/view/34674/36829https://ojs.aaai.org/index.php/AAAI/article/view/34674/36829 1. 概述 文本中的不确定性在许多语境中传达,从日常对话到特定领域的文档(例如医学文档)(Heritage 2013;Landmark、Gulbrandsen 和 Svenevei…...